javascript - 是否可以从 iframe 中检测到 window.close?

标签 javascript html reactjs iframe window.closed

我有一个模式(来 self 的应用程序的 React 组件),在它里面我有一个 iframe。我无法控制 iframe,而且我知道它会在采取某些操作后调用 window.close。有没有办法检测 iframe 中的内容何时调用 window.close,以便我也可以关闭模​​式?

重要提示:我没有使用 jQuery,只使用纯 javascript。

iframe 代码:

      <iframe height='500' width='340'                      
        src='http://content_url'
        ref={(f) => { this.ifr = f; }}>
      </iframe>

有了这个 ref,我可以从我的 React 组件中引用 iframe:

  componentDidMount() {
    this.ifr.onload = () => {
      //whatever action
    };
  }

但是我不能对卸载事件做我想做的事情,因为 iframe 没有被卸载,它只是在里面调用 window.close。

谢谢!

最佳答案

您可以尝试将 window.close 设置为其他一些函数,并在 iframe 调用它时捕获它。

  var closing = window.close;
  window.close = function () {
    console.log('window close fired!');
    closing();
  };

创建事件发射器的更好方法。

  var event = new Event('onCloseWindow');

  // Listen for the event.
  elem.addEventListener('onCloseWindow', function (e) { ... }, false);

  var closing = window.close;
  window.close = function () {
    // Dispatch the event.
    elem.dispatchEvent(event);
    closing();
  };

关于javascript - 是否可以从 iframe 中检测到 window.close?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45946370/

相关文章:

html - 如何使用 HTML/CSS 中的标题制作菜单背景

node.js - 如何将 id 和 body 添加到 axios.PUT 请求中?

javascript - 即使指定了索引,对象中的所有数组值也会在 this.setState 中更新

javascript - 如何删除 html 表格中连续单元格的类

javascript - .slideDown() 不起作用

javascript - 替换的字符串在窗口中显示标签

javascript - 我不知道在这种情况下如何使用 map

javascript - React setState() 不适用于嵌套 DOM 元素

javascript - Gulp mocha Istanbul 尔 免费获得 100%

javascript - 如何在 jQuery 中使用 $ ("body").append() 添加多个 HTML 代码?