javascript - 如何从 IFRAME 中触发 'beforeunload' 事件

标签 javascript reactjs iframe dom-events iframe-app

我有一个应用程序(命名为 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 the beforeunload is sent. This event fires when a window is about to unload 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:

  1. beforeunload (cancellable event)
  2. 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/

相关文章:

reactjs - 来自 React Navigation Drawer 的 React Native Display Modal

javascript - 我如何在 javascript(使用 redux)中构造数据,如果逻辑发生变化,这将消耗更少的内存并且将来可以轻松修改?

javascript - 使用 jQuery/javascript/css 更改 flash 视频对象的属性

javascript - 如何将 wro4j 与 Closure 库和编译器一起使用?

javascript - 如何使用 phantom 钱包和 solana web3js 转移 NFT spl 代币

javascript - React - 复选框输入未正确更新(由于浅合并)

JavaScript - 使用 URL 片段动态调整 iframe 跨域大小

javascript - 为什么 PhoneGap 应用程序中 iframe 内的链接不起作用?

javascript - d3js svg viewBox 不允许计算 window.innerWidth - 170

javascript - 如何在 React v16 中手动调用自定义 PropType 验证器