如何使用 JavaScript 观察 URL 的变化?

Mar*_*377 4 javascript events mutation-observers

Window 事件文档popstate说明:

请注意,仅调用history.pushState()or history.replaceState()不会触发popstate事件。该 popstate事件将通过执行浏览器操作触发,例如单击后退或前进按钮(或调用history.back()history.forward()在 JavaScript 中)。

我需要一种在 URL 更改时通过不触发popstate事件的方式(例如history.replaceState())来执行某些代码的方法。最好使用 MutationObserver API [1],并且绝对不要每 x 秒轮询一次 URL。

此外,hashchange不会这样做,因为我必须对URL 中的每个更改采取行动,而不仅仅是哈希部分。

那可能吗?


[1]在另一个问题上解释为什么 MutationObserver API 对此不起作用。


(其他)相关问题:

dan*_*vis 6

您需要重新定义(包装)history.replaceState另一个脚本正在使用的:

(function(){
  var rs = history.replaceState; 
  history.replaceState = function(){
    rs.apply(history, arguments); // preserve normal functionality
    console.log("navigating", arguments); // do something extra here; raise an event
  };
}());
Run Code Online (Sandbox Code Playgroud)

没有投票,没有浪费,没有重写,没有麻烦。

对 pushState 或编写用户脚本时您希望/需要的任何其他本地程序(如 ajax)执行相同操作。