JS不全记录 - iframe的一些操作

149 阅读1分钟

iframe的一些操作(兼容大多数浏览器的做法)

  1. 在父页面中获取iframe的window对象
// iframeElement.contentWindow
document.querySelector(iframe-class / iframe-id).contentWindow;
// IE
window.frames[iframeId] // iframe的属性ID
window.frames[iframeName] // iframe的属性name
window.frames[iframeIndex] // 下标:从0开始标号的iframe的索引
iframeElement.contentWindow
  1. 在父页面中获取iframe的document对象
// iframeElement.contentDocument -- IE8以下支持
document.querySelector(iframe-class / iframe-id).contentDocument;

// 或者先获取iframe的window对象,再通过window.document来引用(方法一)
let _iframeWindow = document.querySelector(iframe-class / iframe-id).contentWindow.document;

// 方法二
document.querySelector(iframe-class / iframe-id).contentDocument || window.frames[iframeId].contentDocument;
  1. iframe页面获取父页面的window对象
parent: 父页面的window对象
top: 顶层页面的window对象
self: 始终指向当前页面的window对象