HTMLIFrameElement.contentDocument
应用这个办法获取页面iframe中的dom对象,留神可能会有上面两种后果:
- 如果iframe和它的父级在同一个域名下,那么这个办法返回document(是一个嵌套的浏览器上下文环境)
- 如果iframe和它的父级不在同一个域名下,那么这个办法返回null
有了下面的这个准则,咱们就晓得在不跨域的状况下咱们可能更容易的批改iframe外部元素的款式,跨域状况则无奈获取到iframe外部的元素,只能通过其余形式来达到目标(上面会介绍),首先来看下不跨域是怎么做的。
不跨域批改iframe中元素的款式
间接获取到元素批改
let iframeDocument = document.getElementsByTagName("iframe")[0].contentDocument;iframeDocument.body.style.backgroundColor = "blue";// This would turn the iframe blue.
通过下面的操作,把iframe中body的背景色批改为“blue”
在iframe的head中插入样式表
// 页面上有一个id为i1的iframe,它嵌入的是同源的文件 child.html<iframe id="i1" src="./child.html" frameborder="0" width="100%" height="400"></iframe>// 借助jQuery在iframe加载后,向其外部插入style.css$('#i1').load(function () { let cssLink = document.createElement("link"); cssLink.href = "style.css"; cssLink.rel = "stylesheet"; cssLink.type = "text/css"; $('#i1') .contents().find("head") .append($('<link rel="stylesheet" type="text/css" href="style.css">') );});// style.cssbody { background-color: aqua;}
这样咱们就批改了iframe中body的背景色。
跨域状况下批改iframe中元素的款式
应用到的办法如下:
- Window.postMessage()
- window.addEventListener("message",cb())
退出父级页面中引入了一个不同域名下的iframe,须要别离在父级页面发送信息,在iframe页面内监听并解决信息,来间接的批改款式。这是为了保障跨域通信的平安,具体内容参考 这里。
上面介绍具体做法:
如果父级页面引入了一个跨域的iframe,id为i3
<iframe id="i3" src="./cross.html" onload="load()"></iframe>// 在它加载实现后,执行上面的办法function load() { console.log('loaded') activateTheme("light");}// 这里咱们封装了一个activateTheme办法,不便后边复用,作用是批改iframe外部的主题色彩function activateTheme(theme) { var iframe = document.getElementById("i3"); if (iframe && iframe.contentWindow) { iframe.contentWindow.postMessage(theme, "*"); }}
当iframe加载实现后,咱们向它外部传递了activateTheme("light");浅色主题的音讯,上面看下它外部如何接管并做出响应:
// cross.html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>child</title> <style> body, body.theme-light { background-color: #ededed; padding: 1rem; } body.theme-dark { background-color: #444; color: #fff; } </style></head><body> <script> window.addEventListener("message", function (event) { if (event.origin === window.location.origin) { console.log(event.data) document.body.classList = [] document.body.classList.add(`theme-${event.data}`) } }, false ); </script></body></html>
能够看出,咱们在接管到父级传来的音讯,依据音讯的内容来批改了cross.html body的背景色。并且在这里咱们能够做一下是否同源的平安校验。
到这里咱们能够得出一个论断:如果你嵌入的iframe页面和父级不是同一域下,而且你能够在iframe页面中监听事件,这样你能力批改它外部的款式,否则无奈批改。