Cancel onbeforeunload event handler?

Prabesh Shrestha picture Prabesh Shrestha · Jun 8, 2011 · Viewed 27.5k times · Source

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.

Answer

Ibu picture Ibu · Jun 9, 2011

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