Languages
[Edit]
EN

JavaScript - on location changed event / on url changed event

5 points
Created by:
Jacob
532

In this short article, we would like to show how in JavaScript detect if page URL (location object) was changed.

In JavaScript there is no locationchange event, but there are some tricks how to do it.

Quick solution:

// Put following code on the top of head element:

;(function() {
    var pushState = history.pushState;
    var replaceState = history.replaceState;
    history.pushState = function() {
        pushState.apply(history, arguments);
        window.dispatchEvent(new Event('pushstate'));
        window.dispatchEvent(new Event('locationchange'));
    };
    history.replaceState = function() {
        replaceState.apply(history, arguments);
        window.dispatchEvent(new Event('replacestate'));
        window.dispatchEvent(new Event('locationchange'));
    };
    window.addEventListener('popstate', function() {
        window.dispatchEvent(new Event('locationchange'))
    });
})();



// Usage example:

window.addEventListener('locationchange', function(){
    console.log('onlocationchange event occurred!');
})

 

The problem description

With location changed monitoring related are three cases:

  1. when URL is changed in the browser address bar by the user, the whole page is reloaded and there are executed two operations: unload and load page - it is just opening a new page - we can use onload event to do some stuff (check this article),
  2. when location is changed by History API (pushStatereplaceState, popState) in the source code, the page is not reloaded.
    In this case, API doesn't provide any locationchange event - it is necessary to trigger some events manually after the operation, e.g.
    history.pushState(...);
    callEventLogic();  // event on location change
    
    // ...
    
    history.popState(...);
    callEventLogic();  // event on location change
    
    // etc.
  3. when the hash is changed in the URL (location.hash), the page is not reloaded.
    API provides some event to notify that change:
    window.addEventListener('hashchange', function(){
        console.log('onhashchange event occurred!');
    })
    Note: hashchange event is triggered in both chases:
    - on change from source code,
    - on change in the browser address bar by the user.

Summary: it is necessary to add own locationchange event support what is mentioned in second point in above list what was presented in Quick solution too.

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join