通过vanilla JS中的多个iframe来管理DOM [英] Walk up DOM through multiple iframes in vanilla JS

查看:144
本文介绍了通过vanilla JS中的多个iframe来管理DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to be able to walk up the DOM from inside one or more nested iframes to grab and empty the parent div of the top iframe. I'd like my JS to work if there's just one iframe, or if there are two.

我有一个包含这个iframe的主页:

I have a main page with this 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:

and then in ad.html, the page inside the iframe, I have this 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 并清空它。

This walks up the DOM of the containing page till it finds the div with class ad-unit and empties it.

这很好用。但遗憾的是,有时 ad.html 将在第一个嵌套在第一个内部的iframe中提供,因此:

This works nicely. But unfortunately sometimes ad.html will be served inside a second iframe nested inside the first, so:

<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>

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

Can anyone tell me how I can deal with this case? I've tried starting my script with

var el = document;

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

But the DOM walking stops when it gets to the first iframe. How can I continue walking up the DOM irrespective of whether the parent node is a div or an iframe?

推荐答案

如果你不喜欢找到正确的div,你必须使用 iframe (或顶级窗口) href =https://developer.mozilla.org/en-US/docs/Web/API/Window/parent =nofollow> parent

If you don't find the correct div, you have to go up to the next iframe (or top level window) using parent

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 = '';

这篇关于通过vanilla JS中的多个iframe来管理DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆