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);
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.
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 .
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.
This feature is deprecated/obsolete and should not be used.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With