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 without reloading the page. What is the best way to detect if this URL changes?
- Is the
onload
event called again? - Is there an event handler for the URL?
- Or must the URL be checked every second to detect a change?
You are starting a new
setInterval
at each call, without cancelling the previous one - probably you only meant to have asetTimeout
With jquery (and a plug-in) you can do
http://benalman.com/projects/jquery-hashchange-plugin/
Otherwise yes, you would have to use setInterval and check for a change in the hash event (window.location.hash)
Update! A simple draft
use this code
with jQuery
Add a hash change event listener!
Or, to listen to all URL changes:
This is better than something like the code below because only one thing can exist in window.onhashchange and you'll possibly be overwriting someone else's code.
While doing a little chrome extension, I faced the same problem with an additionnal problem : Sometimes, the page change but not the URL.
For instance, just go yo Facebook Home page, and click on 'Home' button. You will reload the page but the URL won't change (one-page app style).
99% of the time, we are developping websites so we can get those events from Frameworks like Angular, React, Vue etc..
BUT, in my case of a Chrome extension (in Vanilla JS), I had to listen to an event that will trigger for each "page change", which can generally be caught by URL changed, but sometimes it doesn't.
My homemade solution was the following :
So basically the leoneckert solution, applied to window history, which will change when a page change in a single page app.
Not rocket science, but cleanest solution I found, considering we are only checking an integer equality here, and not bigger objects or the whole DOM.
Although an old question, the Location-bar project is very useful.