更改 Firefox 中的 window.location.href 以响应 onunload 事件
我在使用 window.location.href
时遇到了一个奇怪的 JavaScript 问题,这显然只影响 Firefox(我使用的是 3.6)。
通常 window.location.href
不是只读的,这在 Firefox 中完美运行:
window.location.href = "http://google.com/";
但是,当我调用函数来响应 onunload
事件时 (),这不会按预期工作:
function testThis() {
alert ("1: " + window.location.href);
window.location.href = "http://google.com/";
alert ("2: " + window.location.href);
return false;
}
在这两种情况下,警报都会显示 Firefox 中页面的当前位置,而不进行更改。没有 JavaScript 错误,并且 onunload
事件成功调用该函数,因此问题似乎是编辑或替换 window.location.href
的值。
我尝试过使用 window.location
、document.location.href
,甚至尝试更改 window.location.search
。是否有可能某个事件(特别是 onunload
事件)导致 window.location.href
变为只读?
I have a strange JavaScript problem using window.location.href
, which apparently only affects Firefox (I'm using 3.6).
Normally window.location.href
would not be read-only, and this works perfectly in Firefox:
window.location.href = "http://google.com/";
However, when I call a function in response to an onunload
event (<body onunload="testThis();">
), this doesn't work as expected:
function testThis() {
alert ("1: " + window.location.href);
window.location.href = "http://google.com/";
alert ("2: " + window.location.href);
return false;
}
In both cases, the alert displays the current location of the page in Firefox, without making the change. There are no JavaScript errors, and the onunload
event successfully calls the function, so the problem appears to be editing or replacing the value of window.location.href
.
I've tried using window.location
, document.location.href
, even tried changing window.location.search
. Is it possible that an event, specifically an onunload
event, causes window.location.href
to become read-only?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,防止恶意网页阻止用户离开。
Yes, to prevent malicious webpages from blocking the user from leaving.
根据记录,firefox 似乎使用 document.location 代替 document.location.href。
For the record, firefox seems to use document.location in lieu of document.location.href.