IFrame是什么?
iframe 标签规定了一个内联框架,可以在当前的文档(页面)中嵌入另外一个文档(页面)。
- 同源情况下:父页面可以访问子页面所有内容
- 不同源情况下:父页面不能访问子页面的内容
--基本使用
<iframe src="http://localhost:8000/2.html"></iframe>
··如何在主元素获取子元素内部的内容(DOM元素、方法等)
ifrascript 标签内me标签可以理解为异步解析的,所以在当前页面执行 容时,此时`iframe`还未渲染成功,也就获取不到其中的 DOM 元素。必须等`iframe.contentWindow.onload`事件触发,`iframe`内部的元素全部加载完成,才能获取 DOM 元素。
···这是父页面 同源下可直接获取 子元素里面的值
<!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>aaa</title>
</head>
<body>
<h1>这是 a 页面</h1>
<iframe src="./b.html" frameborder="0" id="bFrame"></iframe>
<script>
const bFrame = document.getElementById("bFrame");
console.log(bFrame.contentWindow.document.querySelector(".title")); // null
// bFrame.contentWindow 就是 iframe 页面中的 window
// bFrame.contentDocument 就是 iframe 页面中的 document
bFrame.contentWindow.onload = function () {
console.log(bFrame.contentWindow.document.querySelector(".title")); // <h1 class="title">这是 b 页面</h1>
console.log(bFrame.contentDocument.querySelector(".title")); // <h1 class="title">这是 b 页面</h1>
};
</script>
</body>
</html>
iframe src里的子页面 -b.html 与a页面为同级
```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>bbb</title>
</head>
<body>
<h1 class="title">这是 b 页面</h1>
</body>
</html>
```
不同源情况下
- `window.addEventListener("message", function (event) {})` 接受消息
- `window.postMessage(data, targetOrigin)` 发送消息
·····父页面····
<!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>aaa</title>
</head>
<body>
<h1>这是 a 页面</h1>
<button class="btn">给子页面发送消息</button>
<iframe
src="http://localhost:5500/b.html"
frameborder="0"
id="bFrame"
></iframe>
<script>
// 1. 接受子页面的消息
window.addEventListener("message", function (event) {
console.log("接收到子页面传递的消息", event);
});
// 2. 给子页面发送消息
document.querySelector(".btn").onclick = function () {
window.bFrame.contentWindow.postMessage(
"hello child",
"http://localhost:5500"
);
};
</script>
</body>
</html>
····子页面···
子页面向父页面需要用
parents.postMessage()....
<!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>bbb</title>
</head>
<body>
<h1 class="title">这是 b 页面</h1>
<button class="btn">给父页面通信</button>
<script>
// 1. 接受父页面的消息
window.addEventListener("message", function (event) {
console.log("接收到父页面传递的消息", event);
});
// 2. 给父页面发送消息
document.querySelector(".btn").onclick = function () {
window.parent.postMessage('hello father', "http://127.0.0.1:5500");
};
</script>
</body>
</html>