我如何以编程方式触发 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'))
关于Javascript:以编程方式触发 onbeforeunload/onunload 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495381/