javascript - 等待子窗口加载完成

标签 javascript

是否有一个简单的 Hook 来检测脚本打开的窗口是否已完成加载?基本上,我想要相当于 onLoad() Hook ,但我无法直接设置它 - 假设子文档是给定的,并且我实际上无法放置我自己的任何代码就在其中。

例如,假设我有以下两个文件:

parent.html:

<html>
  <head>
    <title>Parent</title>
  </head>
  <script type="text/javascript">
    var w;
    function loadChild() {
      w = window.open();
      w.location.href="child.html";
      // block until child has finished loading... how?
      w.doSomething();
    } 
  </script>
</html>
<body>
  I am a parent window. <a href="javascript:loadChild()">Click me</a>.
</body>

child.html:

<html>
  <head>
    <title>Child</title>
  </head>
  <script type="text/javascript">
    function doSomething() {
      alert("Hi there");
    }
  </script>
</html>
<body>
  I am a child window
</body>

由于设置 location.href 是非阻塞的,所以 w.doSomething() 尚未定义,并且 doSomething() 调用会崩溃。如何检测子进程是否已完成加载?

最佳答案

如果新打开的窗口的位置是同源的,则此方法有效:

var w = window.open('child.html')
w.addEventListener('load', w.doSomething, true); 

关于javascript - 等待子窗口加载完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1372022/

相关文章:

javascript - 如何通过文本框数组提交按钮

javascript - 输入 Prop 不适用于纯函数组件?

javascript - Polymer:页面加载时白屏闪烁

javascript - 语义 UI 的 Webpack 2 问题

javascript - 在样式表 css 之间切换

javascript - 我需要一个 div 从页面右侧的 0 自动边距 div 的右侧填充

javascript - 如何使 ng-repeat 中的元素仅重复一次?

javascript - 使用 function.bind 将函数绑定(bind)到 this

从字符串中拆分并返回值的 Javascript 函数

javascript - 过滤 redux 存储项数组中的重复项