Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 667
Prabesh Shrestha Avatar asked Jun 08 '11 08:06

Prabesh Shrestha


People also ask

How do I cancel Onbeforeunload?

Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What is the difference between Onbeforeunload and Onunload?

onbeforeunload Below are my findings on the iPad; Using window. onunload , I am able to get an alert when user navigates to a different page from myPage. html (either by clicking on some link or doing a Google search while on myPage.

What does window Onbeforeunload do?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.


2 Answers

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

like image 79
Ibu Avatar answered Sep 23 '22 11:09

Ibu


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; 
like image 26
Simon Avatar answered Sep 21 '22 11:09

Simon