iframe 中 beforeunload 事件无法触发的解决方法
由于安全原因,浏览器不允许在 iframe 中触发 'beforeunload' 事件。这是为了防止恶意网站滥用该事件来欺骗用户。
如果您需要在 iframe 中实现类似的功能,可以考虑使用 postMessage API 来与父页面通信。在父页面中可以监听 'beforeunload' 事件,并在需要时通知子页面。
例如,您可以在 iframe 中创建一个监听 'message' 事件的函数,当父页面触发 'beforeunload' 事件时,向 iframe 发送一条消息,告知 iframe 需要执行的操作。
// iframe 中的代码
window.addEventListener('message', function(event) {
if (event.data === 'beforeunload') {
// 执行需要在 iframe 中执行的操作
}
});
// 父页面中的代码
window.addEventListener('beforeunload', function(event) {
// 向 iframe 发送消息
window.frames[0].postMessage('beforeunload', '*');
});
这样,即使 iframe 中无法触发 'beforeunload' 事件,也可以通过 postMessage API 来实现类似的功能。
原文地址: https://www.cveoy.top/t/topic/ohlO 著作权归作者所有。请勿转载和采集!