Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  57] [ 3]  / answers: 1 / hits: 15601  / 7 Years ago, thu, december 21, 2017, 12:00:00

I have a single page app with pagination and filters, and need to detect when the current URL changes at all. Is there not a simple way to add a listener to the current URL and trigger something when it changes? (No setting intervals either!)




  1. User lands on www.foobar.com

  2. User does something, url changes to www.foobar.com?filter=hello

  3. My function runs



I have tried both onhashchange, and tried unbeforeunload, and neither are relevant for this.



window.onbeforeunload = function(e) {
alert ('url changed!');
};

window.onhashchange = function() {
alert ('url changed!');
}


Is there a way to add a listener to the URL, and trigger something anytime it changes at all? (again, single page app so no refresh)


More From » jquery

 Answers
1

If you don't want to use setInterval, you can override the history.pushState event:



(function(history){
const pushState = history.pushState;
history.pushState = function(state) {
if (typeof history.onpushstate == function) {
history.onpushstate({state: state});
}
// Call your custom function here
return pushState.apply(history, arguments);
}
})(window.history);

[#55622] Monday, December 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;