在 vanilla JS 中遍历多个 iframe DOM
Walk up DOM through multiple iframes in vanilla JS
我希望能够从一个或多个嵌套 iframe 中向上移动 DOM 以获取并清空顶部 iframe 的父级 div。如果只有一个 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 向上移动,直到找到带有 class 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?
如果您没有找到正确的 div,您必须使用 parent
[= 进入下一个 iframe
(或顶级 window
) 15=]
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 = '';
我希望能够从一个或多个嵌套 iframe 中向上移动 DOM 以获取并清空顶部 iframe 的父级 div。如果只有一个 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 向上移动,直到找到带有 class 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?
如果您没有找到正确的 div,您必须使用 parent
[= 进入下一个 iframe
(或顶级 window
) 15=]
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 = '';