Javascript: Programmatically trigger onbeforeunload/onunload event

你说的曾经没有我的故事 提交于 2019-12-24 11:27:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!