How can I check if a URL has changed in JavaScript? For example, websites like GitHub, which use AJAX, will append page information after a # symbol to create a unique URL w
I wanted to be able to add locationchange
event listeners. After the modification below, we'll be able to do it, like this
window.addEventListener('locationchange', function(){
console.log('location changed!');
})
In contrast, window.addEventListener('hashchange',()=>{})
would only fire if the part after a hashtag in a url changes, and window.addEventListener('popstate',()=>{})
doesn't always work.
This modification, similar to Christian's answer, modifies the history object to add some functionality.
By default, there's a popstate
event, but there are no events for pushstate
, and replacestate
.
This modifies these three functions so that all fire a custom locationchange
event for you to use, and also pushstate
and replacestate
events if you want to use those:
/* These are the modifications: */
history.pushState = ( f => function pushState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.pushState);
history.replaceState = ( f => function replaceState(){
var ret = f.apply(this, arguments);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.replaceState);
window.addEventListener('popstate',()=>{
window.dispatchEvent(new Event('locationchange'))
});