Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Programmatically trigger onbeforeunload/onunload event

How can I programmatically trigger onbeforeunload and onunload events?(No jquery please). I've tried:

var event = new Event('onbeforeunload');
event.initEvent("onbeforeunload", true, true);
window.document.dispatchEvent(event);
like image 443
Alex Avatar asked Jul 18 '15 20:07

Alex


People also ask

How do I trigger a Beforeunload event?

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 the difference between Onbeforeunload and Onunload?

One significant difference (other than cancelability) between the onbeforeunload and onunload is that the former is triggered for download links and the latter is not. Example: <a href="https://somewhere.com/thething.zip">download</a> will trigger the onbeforeunload handler, but not the onunload .

What is Onbeforeunload in JS?

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.

Can I use Onbeforeunload?

This feature is deprecated/obsolete and should not be used.


1 Answers

window.dispatchEvent(new Event('beforeunload'))

I think this would be the best way in 2020. In case anyone finds this.

window.addEventListener('beforeunload',()=>{console.log("beforeunload triggered")})
window.dispatchEvent(new Event('beforeunload'))
like image 65
user301441 Avatar answered Oct 18 '22 10:10

user301441