Cancel onbeforeunload event handler?

无人久伴 提交于 2019-12-19 05:06:48

问题


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.


回答1:


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




回答2:


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;



回答3:


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');



回答4:


To add:

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

To remove:

window.removeEventListener("beforeunload", f_beforeunload);


来源:https://stackoverflow.com/questions/6275983/cancel-onbeforeunload-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!