How to detect if URL has changed after hash in JavaScript

后端 未结 17 1422
無奈伤痛
無奈伤痛 2020-11-22 17:02

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

17条回答
  •  感情败类
    2020-11-22 17:43

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

提交回复
热议问题