Search code examples
javascripteventsonbeforeunload

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);


Solution

  • Either use

    object.onunload=function(){myScript};
    

    or the addEventListener() method:

    object.addEventListener("unload", myScript);
    

    to trigger the event use object.unload();