Skip to content Skip to sidebar Skip to footer

Javascript: Programmatically Trigger Onbeforeunload/onunload Event

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

Solution 1:

window.dispatchEvent(newEvent('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(newEvent('beforeunload'))

Solution 2:

Either use

object.onunload=function(){myScript};

or the addEventListener() method:

object.addEventListener("unload", myScript);

to trigger the event use object.unload();

Post a Comment for "Javascript: Programmatically Trigger Onbeforeunload/onunload Event"