gpt4 book ai didi

javascript - 从外部检测 AngularJS onHashChange 事件

转载 作者:行者123 更新时间:2023-12-04 18:08:02 25 4
gpt4 key购买 nike

我正在尝试在使用标准 ui-router 的 AngularJS 应用程序之外监听 url 修改事件。由于 Angular 更新位置 hash,我假设它会触发 onhashchange 事件。但是,在 Mac 上最新的 Chrome/Firefox 中,它永远不会。

我所看到的(在 Chrome 中)是为初始加载触发一次的 popstate 事件:

$(window).on('hashchange', function(){
console.log('hashchange'); // Never fired
});
$(window).on('popstate', function(){
console.log('popstate'); // Only fires on initial app load
});

在 Angular 代码本身之外,我可以监听不同的事件吗?

最佳答案

根据证据,它似乎正在使用 pushState 并且该方法没有触发任何事件,因此我找到的唯一解决方案是覆盖 pushState 方法并触发自定义事件:

// Custom pushState event
(function(history){
var pushState = history.pushState;
history.pushState = function(state){
$(window).trigger('pushState');
return pushState.apply(history, arguments);
};
})(window.history);

$(window).on('pushState', function(event){
console.log('hashchange');
});

关于javascript - 从外部检测 AngularJS onHashChange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21769156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com