我有一个应用程序(命名为 B),它被另一个主应用程序(命名为 A 或父应用程序)嵌入到 Iframe 中。
So: App A-- // domain of A: https://mydomain/mainApp
|___ App B in Iframe // domain in B: https://mydomain/appB
问题是:然后主/父应用程序有一个导航菜单。单击一个项目时,会创建一个带有 SRC 属性的 Iframe,在其中加载 App B。
当用户点击应用程序 A 中菜单的另一个选项时,Iframe 被销毁,React 中的另一个内容 View 出现,取代了 Iframe。
执行此操作时,B 中用户在表单中键入的所有数据都消失了,因为我无法触发 B 中的保存事件。
我在 iframe 应用程序中添加了以下事件处理程序:
window.addEventListener("beforeunload", function (e) {
// Trigger here the save settigns event inside B
});
但当用户浏览主应用程序菜单时,以前的代码永远不会触发。如我所见,应用程序 A 中的导航菜单更改了浏览器中的 URL(但似乎是 SPA React.js 路由或类似路由,没有真正的重定向)。
问题是:Iframe 能否检测到何时卸载/销毁以首先触发 Ajax 中的保存设置? P.S: 我无权访问 App A 代码。
提前致谢
最佳答案
来自 MDN :
The
WindowEventHandlers.onbeforeunload
event handler property contains the code executed when thebeforeunload
is sent. This event fires when a window is about tounload
its resources. The document is still visible and the event is still cancelable.
The
unload
event is fired when the document or a child resource is being unloaded. It is fired after:
beforeunload
(cancellable event)pagehide
例子:
<body>
<input type="button" id="removeIframeBtn" value="remove iframe"/>
<iframe id="iframe" src="http://localhost:8080/iframe.html"></iframe>
</body>
<script>
const removeIframeBtn = document.getElementById("removeIframeBtn");
const iframe = document.getElementById("iframe");
iframe.contentWindow.onbeforeunload = function () {
debugger;
};
window.onbeforeunload = function () {
debugger;
};
removeIframeBtn.onclick = function () {
iframe.remove();
};
</script>
假设带有当前代码的页面在浏览器选项卡中打开。
如果您尝试关闭此选项卡,将调用 iframe.contentWindow.onbeforeunload
。
如果您尝试单击 remove iframe
btn,iframe
将从文档中删除,但 iframe.contentWindow.onbeforeunload
不会调用。没有 unload
事件。
React 使用 js 渲染组件,所以它完全像第二种情况,点击 remove iframe
btn。
所以你的问题的答案是:在单页应用程序的路由更改时,无法通过 onbeforeunload
事件检测到 iframe 的卸载。
您的解决方案是在每次更改时保存设置。
关于javascript - 如何从 IFRAME 中触发 'beforeunload' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49445671/