Javascript 如何拦截window.location变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2073086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:39:57  来源:igfitidea点击:

How to intercept window.location change

javascriptjquery

提问by epitka

I need a way to attach some pre-processing to each assignment of the window.location. Is there a way to do this. I basically need to serialize some info, that will be used in the new location.

我需要一种方法来为 window.location 的每个分配附加一些预处理。有没有办法做到这一点。我基本上需要序列化一些信息,这些信息将在新位置使用。

采纳答案by Hackles

You can use the beforeunloadevent to trigger your code to run prior to navigation... If you need something more specific (e.g., only navigations initiated in your code), then I recommend that you factor out code changing window.locationinto a separate function, and add a hook for your custom logic.

您可以使用该beforeunload事件触发您的代码在导航之前运行...如果您需要更具体的内容(例如,仅在您的代码中启动导航),那么我建议您将代码更改window.location为单独的函数,并添加自定义逻辑的钩子。

回答by Russ Cam

You may want to look at Ben Nadel's post in regard to doing this, it may be exactly what you're looking for

你可能想看看 Ben Nadel 的关于这样做的帖子,这可能正是你要找的

Binding Events to non DOM objects with jQuery

使用 jQuery 将事件绑定到非 DOM 对象

His example in the post talks about creating an event handler that triggers a change event when window.locationchanges

他在关于创建一个事件处理程序触发change事件时,后会谈例如window.location改变