开发者

Cancel onbeforeunload event handler?

I have an onbeforeunload event handler attached to the page which executes every time the page reloads / gets redirected.

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.


In javascript functions can be overwritten. You can simply assign it a new purpose:

window.onbeforeunload = function () {
  // blank function do nothing
}

This will completely overwrite the existing version of 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


To add:

function f_beforeunload(e) {console.log("do something");}
window.addEventListener("beforeunload", f_beforeunload);

To remove:

window.removeEventListener("beforeunload", f_beforeunload);


Not immediately related to this question, but may help someone nevertheless. This is what I use in Angular 1.x and TypeScript:

this.$window.onbeforeunload = () => undefined;


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,

$('#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" )

$( window ).off( "unload", handler )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜