Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbind window.onbeforeunload() cancel

i'm binding a function to an event with

window.onbeforeunload = function() {
 somefunction()
}

which is working on unload as planned, but if they cancel the onbeforeunload the function is still attached, is it possible to check if the user cancels onbeforeunload

like image 915
James Kirkby Avatar asked Nov 18 '13 20:11

James Kirkby


People also ask

How do you cancel Windows 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.

How do I stop Onbeforeunload event during the page refresh?

You can't. A page refresh is like navigating away and unloading the DOM so the onbeforeunload event will always be called.

What triggers Onbeforeunload?

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.

What is 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.


2 Answers

Actually, I found it was quite easy: I just set

window.onbeforeunload = null;

for each click before it was run, allowing the event handler to be run afterwards.

like image 66
James Kirkby Avatar answered Oct 11 '22 03:10

James Kirkby


or you can just return null

window.onbeforeunload = function() {
  return null;
};

I am using following snippet for that: window.onbeforeunload gist

like image 41
woss Avatar answered Oct 11 '22 01:10

woss