以编程方式触发onbeforeunload/onunload事件

Javascript: Programmatically trigger onbeforeunload/onunload event

本文关键字:onunload 事件 onbeforeunload 编程 方式触      更新时间:2023-09-26

如何以编程方式触发onbeforeunload和onunload事件?(请不要使用jquery)。我试过了:

var event = new Event('onbeforeunload');
event.initEvent("onbeforeunload", true, true);
window.document.dispatchEvent(event);

window.dispatchEvent(new Event('beforeunload'))

我认为这将是2020年最好的方式。如果有人发现这个。

window.addEventListener('beforeunload',()=>{console.log("beforeunload triggered")})
window.dispatchEvent(new Event('beforeunload'))

使用

object.onunload=function(){myScript};

或addEventListener()方法:

object.addEventListener("unload", myScript);

触发事件使用object.unload ();