简体   繁体   English

URL 更改事件 - JavaScript

[英]URL Change Event - JavaScript

I have a setTimeout that records the URL in a variable called newURL .我有一个setTimeout将 URL 记录在一个名为newURL的变量中。

function checkURL() {
    var newURL = window.location;
} setInterval(checkURL, 1000);

What I would like to happen, is that a certain function must be executed, when the URL changes.我想要发生的是,当 URL 更改时,必须执行某个函数。 Could someone help me here please?有人可以帮我吗?

Not sure why the page wouldn't reload before you could catch the change in the url.不知道为什么在您能捕捉到 url 中的更改之前页面不会重新加载。 You can also take a look a window.onunload你也可以看看window.onunload

var checkURL = (function () {
    var oldURL = location.href;
    return function (fn) {
        var newURL = location.href;
        if (fn && oldURL !== newURL) {
            fn(oldURL, newURL);
        }
        oldURL = newURL;
    };
}());

From what i understand, when the url changes will be a new execution of the JS scripts in that page.据我了解,当 url 更改时,将在该页面中重新执行 JS 脚本。 The " window.location" will return the current URL, but JavaScript not record /register data in script, or variablle from a page to another. “window.location”将返回当前的 URL,但 JavaScript 不会在脚本中记录 /register 数据,或者从一个页面到另一个页面的变量。

Use a global variable to store old url.使用全局变量来存储旧的 url。 Than you can check if the url was changed and execute some function.然后您可以检查 url 是否已更改并执行某些功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM