问题
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);
回答1:
Either use
object.onunload=function(){myScript};
or the addEventListener() method:
object.addEventListener("unload", myScript);
to trigger the event use object.unload();
回答2:
window.dispatchEvent(new Event('beforeunload'))
I think this would be the best way now. In case anyone finds this.
window.addEventListener('beforeunload',()=>{console.log("beforeunload triggered")})
window.dispatchEvent(new Event('beforeunload'))
来源:https://stackoverflow.com/questions/31495381/javascript-programmatically-trigger-onbeforeunload-onunload-event