Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

JavaScript - on location changed event / on url changed event

0 contributions
4 points

In this short article we would like to show how to detect if page url (location object) changed with JavaScript.

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'))
    });
})();

// Example usage:

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

Bettrer problem description

With location changed monitoring related are three cases:

  1. when url is changed from browser UI by user, whole page is reloaded and there are executed two operations: unload and load page - it is just opening new page,
  2. location changed by History API (pushStatereplaceState, popState) doesn't cause page realoading. API doesn't provide any locationchange event too. It is necessary to call some logic after the methods, e.g.
    history.pushState(...);
    callEventLogic();
    
    // ...
    
    history.popState(...);
    callEventLogic();
    
    // etc.
  3. hash changed in url (location.hash) is provided by separated event:
    window.addEventListener('hashchange', function(){
        console.log('onhashchange event occurred!');
    })

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.

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more