关于前端:修改iframe内部元素的样式

8次阅读

共计 2300 个字符,预计需要花费 6 分钟才能阅读完成。

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.css
body {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 页面中监听事件,这样你能力批改它外部的款式,否则无奈批改。

正文完
 0