How to detect if URL has changed after hash in JavaScript

后端 未结 17 1626
無奈伤痛
無奈伤痛 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:32

    EDIT after a bit of researching:

    It somehow seems that I have been fooled by the documentation present on Mozilla docs. The popstate event (and its callback function onpopstate) are not triggered whenever the pushState() or replaceState() are called in code. Therefore the original answer does not apply in all cases.

    However there is a way to circumvent this by monkey-patching the functions according to @alpha123:

    var pushState = history.pushState;
    history.pushState = function () {
        pushState.apply(history, arguments);
        fireEvents('pushState', arguments);  // Some event-handling function
    };
    

    Original answer

    Given that the title of this question is "How to detect URL change" the answer, when you want to know when the full path changes (and not just the hash anchor), is that you can listen for the popstate event:

    window.onpopstate = function(event) {
      console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
    };
    

    Reference for popstate in Mozilla Docs

    Currently (Jan 2017) there is support for popstate from 92% of browsers worldwide.

提交回复
热议问题