Javascript 取消 onbeforeunload 事件处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6275983/
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
Cancel onbeforeunload event handler?
提问by Prabesh Shrestha
I have an onbeforeunload event handler attached to the page which executes every time the page reloads / gets redirected.
我有一个 onbeforeunload 事件处理程序附加到页面,每次页面重新加载/重定向时都会执行。
window.onbeforeunload = function() {
console.log("do something");}
I do not want this script to run during my tests. I want to disable it in my own test environment.
我不希望这个脚本在我的测试期间运行。我想在我自己的测试环境中禁用它。
Is there some way to unbind this onbeforeunload event? I am using JavaScript, with jQuery as the framework, so an answer in jQuery would be good.
有没有办法解除这个 onbeforeunload 事件的绑定?我正在使用 JavaScript,以 jQuery 作为框架,因此 jQuery 中的答案会很好。
回答by Ibu
In javascript functions can be overwritten. You can simply assign it a new purpose:
在 javascript 函数中可以被覆盖。您可以简单地为其分配一个新用途:
window.onbeforeunload = function () {
// blank function do nothing
}
This will completely overwrite the existing version of window.onbeforeunload
.
这将完全覆盖现有版本的window.onbeforeunload
.
Note: Why don't you simply remove the line of code that sets this function in the first place? Or if you can't, you will have to set this blank function after it is has been defined, just to make sure it is not overridden again
注意:为什么不首先删除设置此函数的代码行?或者,如果不能,则必须在定义后设置此空白函数,以确保它不会再次被覆盖
回答by Simon
Not immediately related to this question, but may help someone nevertheless. This is what I use in Angular 1.x and TypeScript:
与这个问题没有直接关系,但仍然可以帮助某人。这是我在 Angular 1.x 和 TypeScript 中使用的:
this.$window.onbeforeunload = () => undefined;
回答by murthy naika k
jQuery ≥ 1.7
jQuery ≥ 1.7
With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,
从 jQuery 1.7 开始,事件 API 已更新,.bind()/.unbind() 仍可用于向后兼容,但首选方法是使用 on()/off() 函数。下面是,
$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');
$( window ).on( "unload", handler )
As the .unload() method is just a shorthand for .on( "unload", handler ), detaching is possible using .off( "unload" )
由于 .unload() 方法只是 .on( "unload", handler ) 的简写,因此可以使用 .off( "unload" ) 进行分离
$( window ).off( "unload", handler )
回答by Oleksandr Potomkin
To add:
加上:
function f_beforeunload(e) {console.log("do something");}
window.addEventListener("beforeunload", f_beforeunload);
To remove:
去除:
window.removeEventListener("beforeunload", f_beforeunload);