AJ00200 AJ00200 - 15 days ago 5
Javascript Question

How to detect URL change in JavaScript

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?


Answer

In modern browsers(IE8+, FF3.6+, Chrome), you can just listen to the hashchange event on window.

In some old browsers, you need a timer that continually checks location.hash. If you're using jQuery, there is a plugin that does exactly that.