0

我有一个 iframe 正在呈现来自另一个域的内容。显然我无法contentDocument从其他域访问(返回null)。但是当用户对呈现的 iframe 执行操作时,它会重定向回我的域。因此,那时我可以阅读该文档。基本上一旦 contentDocument 不是null,我想执行一个动作。

目前我只是想在 iframe 的孩子(在这种情况下它contentDocument发生变异......

window.onload = () => {
  setTimeout(initializeObserver, 2000)
}

const initializeObserver = () => {
  const iframe = document.getElementById('my_iframe')

  observer.observe(
    iframe,
    {
      attributes: true,
      childList: true,
      subtree: true
    }
  )
}

const observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    if(mutation.addedNodes.length) {
      alert("SOMETHING HAPPENED!")
    }
  })
})

但是即使添加了子节点并且 iframe 中的元素发生了变化,警报也不会触发。我读过很多例子,但也许我仍然想念它是如何工作的。有人可以帮助解释为什么这个观察者没有触发突变吗?

提前致谢

4

1 回答 1

1

当 an<iframe>中的浏览上下文location发生变化时,src包含的属性<iframe>不会改变,因此您的页面看不到任何差异。

由于您显然控制了另一个页面,因此您可以做的就是将消息发布到您的主页。
然后你只需要听那个消息,你就知道你的框架已经回来了。

// in main
addEventListener("message", (evt) => {
  if( evt.origin === location.origin && evt.data === "I'm back" ) {
    // your page came back
  }
});
// in framed page
top.postMessage( "I'm back", location.origin );
于 2021-02-15T04:01:23.490 回答