【问题标题】:Listener event for when URL parameters changeURL 参数更改时的侦听器事件
【发布时间】:2018-06-03 16:42:27
【问题描述】:

我有一个带有分页和过滤器的单页应用程序,需要检测当前 URL 何时发生变化。有没有一种简单的方法可以将监听器添加到当前 URL 并在它更改时触发某些东西? (也没有设置间隔!)

  1. 用户登陆 www.foobar.com
  2. 用户做某事,网址更改为 www.foobar.com?filter=hello
  3. 我的函数运行

我已经尝试过 onhashchange 和 unbeforeunload,但都与此无关。

window.onbeforeunload = function(e) {
   alert ('url changed!');
};

window.onhashchange = function() { 
alert ('url changed!');  
}

有没有办法给 URL 添加一个监听器,并在它发生任何变化时触发一些东西? (再次,单页应用,所以没有刷新)

【问题讨论】:

  • 我看过了 - 那是一个“onhashchange”场景。我的有点不同,没有哈希,我不想设置间隔。
  • @klugjo nope - 因为网址中有一个 has 。这里只是参数。

标签: javascript jquery listener addeventlistener


【解决方案1】:

如果不想使用 setInterval,可以覆盖history.pushState 事件:

(function(history){
    const pushState = history.pushState;
    history.pushState = function(state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
        // Call your custom function here
        return pushState.apply(history, arguments);
    }
})(window.history);

【讨论】:

  • 这越来越近了!虽然它给了我一个控制台错误 Uncaught TypeError: Failed to execute 'pushState' on 'History': 2 arguments required, but only 1 present。它可能与网站上的其他代码冲突...
  • 为什么是History,不应该是history 吗?没有大写
  • 箭头函数不暴露arguments对象,你必须使用history.pushState = (state, ...args) => {pushState.call(history, state, ...args);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 2014-01-07
  • 2011-01-11
  • 2018-09-04
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
相关资源
最近更新 更多