
跨标签通信
1、首先讲一讲我们的同源策略,是浏览器提出的保护各个标签页的内容不受别人窃取并且恶意操作
同源策略:简单理解就是端口,协议,域名三个全部相同
2、跨域
既然刚开始说了,我们安全并且有效的去进行两个页面的通信呢?下面博主讲几个方法简单讲一下
1、window.open,window.postMessgae
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>index1页面</title>
</head>
<body>
<!-- 1、window.open,window.postMessage进行跨标签通信 -->
<button id="popBtn">弹出新的窗口</button>
<input type="text" id="content" />
<button id="sendbtn">发送</button>
<script>
// 1.创建一个新的窗口
let popBtn = document.getElementById("popBtn");
let content = document.getElementById("content");
let sendbtn = document.getElementById("sendbtn");
let opener = null; //用于保存window.open返回的窗口对象
popBtn.onclick = function () {
opener = window.open(
"index2.html",
"新的窗口",
"width=600,height=600"
);
};
sendbtn.onclick = function () {
let data = {
name: content.value,
};
// data代表的是要发送的数据
// 第二个参数是,origin,代表的是目标窗口的域名
opener.postMessage(data, "*");
};
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>index2页面</title>
</head>
<body>
<!-- 1、window.open,window.postMessage进行跨标签通信 -->
<h1>
这是页面2
</h1>
<script>
window.addEventListener('message', function (e) {
console.laog(e.data);
})
</script>
</body>
</html>
2、BroadcastChannel跨标签通信
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>index1页面</title>
</head>
<body>
<!-- 2、BroadcastChannel 跨标签通信-->
<h1>这是页面1</h1>
<button id="sendBtn">发送</button>
<input type="text" id="content" />
<script>
let sendBtn = document.getElementById("sendBtn");
let content = document.getElementById("content");
let bc = new BroadcastChannel("myChannel");
sendBtn.onclick = function () {
let data = {
name: content.value,
};
bc.postMessage(data);
};
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>index2页面</title>
</head>
<body>
<!--2、BroadcastChannel 跨标签通信 -->
<h1>这是页面2</h1>
<script>
let bc = new BroadcastChannel("myChannel");
bc.onmessage = function (e) {
console.log(e.data);
}
</script>
</body>
</html>
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 Fireworks
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果