跳到主要内容

跨域跨标签页通信实战

· 阅读需 1 分钟
  1. 先用 browser-sync 创建三个不同源的服务器
const browserSync = require("browser-sync");
const bs = browserSync.create();

const serve = () => {
bs.init({
port: 8081, // 8082 8083
server: {
baseDir: ".",
},
});
};

module.exports = {
serve,
};
  1. 使用 gulp 启动
  2. 8081 作为数据接收方
<!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>Document</title>
</head>
<body>
<h1>page1</h1>
<iframe src="http://localhost:8083" style="display: none;"></iframe>
</body>
</html>
<script>
window.addEventListener("message", function(e) {
console.log(e.data);
});
</script>
  1. 8082 作为数据发送方
<!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>Document</title>
</head>
<body>
<h1>page2</h1>
<iframe src="http://localhost:8083" style="display: none;"></iframe>
</body>
</html>
<script>
let i = 0;
setInterval(() => {
window.frames[0].window.postMessage(i++, "http://localhost:8083");
}, 1000);
</script>
  1. 8083 作为中转方
<!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>Document</title>
</head>
<body></body>
</html>
<script>
const bc = new BroadcastChannel("Port");
window.addEventListener("message", function(e) {
bc.postMessage(e.data);
});

bc.addEventListener("message", function(e) {
window.parent.postMessage(e.data, "\*");
});
</script>