Javascript 有没有办法在更改 window.location.href 后进行 onload 回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13811582/
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-24 14:50:15  来源:igfitidea点击:

Is there a way to have an onload callback after changing window.location.href?

javascriptonloadwindow.location

提问by Lukas

Essentially what I'd like to do is something to the effect of this:

本质上,我想做的事情是这样的:

window.location.href = "some_location";
window.onload = function() {
  alert("I'm the new location and I'm loaded!");
};

Is there any way to have a callback when the window's new location is loaded? (The above code doesn't work.)

当窗口的新位置被加载时,有没有办法进行回调?(上面的代码不起作用。)

采纳答案by jfriend00

No, you cannot do it the way you want. Loading a new page closes the current document and starts loading a new document. Any code in your current document will no longer be active when the new page starts to load.

不,你不能按照你想要的方式去做。加载新页面会关闭当前文档并开始加载新文档。当新页面开始加载时,当前文档中的任何代码都将不再处于活动状态。

To have an event handler when the new document loads, you would either need to insert code into the new page's document or load the new document into an iframe and monitor the loading of the iframe from your current document.

要在加载新文档时使用事件处理程序,您需要将代码插入到新页面的文档中,或者将新文档加载到 iframe 中并监视从当前文档加载 iframe。

回答by mattgmg1990

Setting window.location.href to a new value tells the browser to simply go to the next page.

将 window.location.href 设置为新值会告诉浏览器直接转到下一页。

Like so:

像这样:

window.location.href = "http://www.google.com/";

Once the browser goes to google.com, that's it, your Javascript is no longer executing, and there is no way for you to have any sort of callback, because the browser is no longer running your page.

一旦浏览器转到 google.com,就是这样,您的 Javascript 不再执行,并且您无法进行任何类型的回调,因为浏览器不再运行您的页面。

So, the answer is no.

所以,答案是否定的。