How to detect if URL has changed after hash in JavaScript

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

    The answer below comes from here(with old javascript syntax(no arrow function, support IE 10+)): https://stackoverflow.com/a/52809105/9168962

    (function() {
      if (typeof window.CustomEvent === "function") return false; // If not IE
      function CustomEvent(event, params) {
        params = params || {bubbles: false, cancelable: false, detail: null};
        var evt = document.createEvent("CustomEvent");
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
        return evt;
      }
      window.CustomEvent = CustomEvent;
    })();
    
    (function() {
      history.pushState = function (f) {
        return function pushState() {
          var ret = f.apply(this, arguments);
          window.dispatchEvent(new CustomEvent("pushState"));
          window.dispatchEvent(new CustomEvent("locationchange"));
          return ret;
        };
      }(history.pushState);
      history.replaceState = function (f) {
        return function replaceState() {
          var ret = f.apply(this, arguments);
          window.dispatchEvent(new CustomEvent("replaceState"));
          window.dispatchEvent(new CustomEvent("locationchange"));
          return ret;
        };
      }(history.replaceState);
      window.addEventListener("popstate", function() {
        window.dispatchEvent(new CustomEvent("locationchange"));
      });
    })();
    

提交回复
热议问题