【问题标题】:Detect when the iframe inside another iframe is loaded from third(parent) iframe检测何时从第三个(父)iframe 加载另一个 iframe 中的 iframe
【发布时间】:2018-02-09 19:14:02
【问题描述】:

Brainf... 使用 iframe。

所以,当前页面结构:

page -> main_iframe -> iframe1 -> iframe2

脚本在“main_iframe”中执行。 这个“main_iframe”有“iframe1”,“iframe1”里面有“iframe2”:

我想更改 iframe2 的 width=100%,它在 iframe1 内,它在 main_iframe 内

所以我在“main_iframe”执行以下 js,它可以工作:

document.querySelector('#iframe1').onload = function() {

setTimeout(function(){
        document.querySelector('#iframe1').contentDocument.querySelectorAll("iframe")[0].style.width = '100%';
 }, 3000); 

}

但是如何删除超时计时器,以便在 iframe2 加载后立即呈现?

我尝试了以下方法:

document.querySelector('#iframe1').onload = function() {

document.querySelector('#iframe1').contentDocument.querySelectorAll("iframe")[0].onload = function () {
        document.querySelector('#iframe1').contentDocument.querySelectorAll("iframe")[0].style.width = '100%';
  }

};

但如果没有运气,onload 触发后什么也没有发生。

【问题讨论】:

  • 首先,从选择器中删除空格 -> querySelectorAll(" iframe") 之后,删除第二个 onload(第一个 onload 中的那个),因为您不需要等待 frame2 的内容在将宽度设置为 frame1 的 100% 之前加载。
  • @Archer 空间已修复(错误仅在 stackoverflow 发布时出现)。因此,在删除第二次加载后,它必须以简单的 document.contentDocument.... 开头,您的意思是 document.contentDocument.querySelectorAll("iframe")[0].style.width = '100%';

标签: javascript iframe settimeout


【解决方案1】:

您可以在 load 事件处理程序中使用 this 引用外部 iframe,这样会更整洁一些。这应该可以满足您的需求...

document.querySelector("#iframe1").addEventListener("load", function() {
    this.contentDocument.querySelector("iframe").style.width = "100%";
});

【讨论】:

  • 感谢 Archer,实际上它可以工作,但有时会设置 style.width,有时不会。嗯
  • 这里的未知数太多了。你能把你的问题写成minimal reproducible example吗?
  • 这是与广告相关的问题,广告通过 iframe 进行瀑布式(回传)。我不能做最小的例子,因为:当我试图在几个 html 标签(或我自己的 vps)上本地模拟问题时,你建议我的代码运行良好,内部 iframe 将它的 style.width 设置为 100%,但是当我在现场(巨大,充满 iframe 和其他媒体)网站(不是我的,我只能将 .js 添加到第一个 iframe 源代码)上尝试时 - 然后出现问题。很抱歉造成混乱的情况。
  • 我可以分享你到公共页面的链接(但是你需要.LV国家的代理才能看到问题)......我认为你不值得从那开始。无论如何,您已经回答了有关给定 iframe 情况的问题。非常感谢!
  • 不用担心 - 很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
相关资源
最近更新 更多