【问题标题】:Walk up DOM through multiple iframes in vanilla JS在 vanilla JS 中通过多个 iframe 走上 DOM
【发布时间】:2016-02-27 01:24:12
【问题描述】:

我希望能够从一个或多个嵌套 iframe 中向上走 DOM,以抓取并清空顶部 iframe 的父 div。如果只有一个 iframe,或者有两个 iframe,我希望我的 JS 能够正常工作。

我有一个带有这个 iframe 的主页:

<div class="ad-unit">
  <div class="ad-unit-large">
    <iframe width="970" height="250" src="ad.html"></iframe>
  </div>
</div>

然后在ad.html,iframe 内的页面,我有这个 JavaScript:

function getAdSlot() {
  var el = window.frameElement.parentNode;
  for (; el; el = el.parentNode) {
    if (el.classList && el.classList.contains('ad-unit')) return el;
  }
  return false;
}

var el = getAdSlot();
console.log(el);
el.innerHTML = '';

这会遍历包含页面的 DOM,直到找到类为 ad-unit 的 div 并将其清空。

这很好用。但不幸的是,有时ad.html 会在嵌套在第一个 iframe 中的第二个 iframe 中提供,所以:

<div class="ad-unit">
  <div class="ad-unit-large">
    <iframe width="970" height="250" src="frame.html"></iframe>
  </div>
</div>

frame.html 将包含:

<iframe width="970" height="250" src="ad.html"></iframe>

谁能告诉我如何处理这个案子?我试过用

开始我的脚本
var el = document;

但是当 DOM 到达第一个 iframe 时,它​​会停止行走。无论父节点是 div 还是 iframe,我如何才能继续向上移动 DOM?

【问题讨论】:

  • 我不认为你可以这样做 - 看起来这可能是一个安全漏洞。
  • @NG。如果来自同一个域,则不是安全漏洞

标签: javascript html dom iframe dom-traversal


【解决方案1】:

如果找不到正确的 div,则必须使用 parent 上到下一个 iframe(或顶级 window

function getAdSlot(win) {
  var el = win.frameElement.parentNode;
  for (; el; el = el.parentNode) {
    if (el.classList && el.classList.contains('ad-unit')) return el;
  }
  // Reached the top, didn't find it 
  if (parent === top) {
     return false;
  }
  // Try again with the parent window 
  return getAdSlot(parent);
}
var el = getAdSlot();
console.log(el);
el.innerHTML = '';

【讨论】:

  • 天才!非常感谢胡安,我接受了。我只需要将窗口参数添加到函数的初始调用中 - var el = getAdSlot(window);
猜你喜欢
  • 2019-03-12
  • 2011-03-30
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 2021-12-15
  • 2023-03-28
  • 2011-09-13
  • 1970-01-01
相关资源
最近更新 更多