跳到主要内容

postMessage 跨域方案

准备


分别用vite搭建两个项目

  1. 安装vite

    yarn add vite -S 
  2. 编辑命令行

    {
    "name": "a",
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "scripts": {
    "start":"vite"
    },
    "dependencies": {
    "vite": "^2.9.12"
    }
    }

语法


a 页面

<!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>
<h3>a 页面</h3>
<iframe src="http://localhost:3001" frameborder="0" id="iframe"></iframe>
<script>
const iframe = document.getElementById("iframe");
iframe.addEventListener("load", function () {
const data = {
id: "b",
title: "b 页面",
};
iframe.contentWindow.postMessage(
JSON.stringify(data),
"http://localhost:3001"
);
});
window.addEventListener("message", function (e) {
console.log(e.data);
});
</script>
</body>
</html>

b 页面

<!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>
<h3>b 页面</h3>
<script>
window.addEventListener("message", function (e) {
console.log(e.data);
const data = {
message: "b 页面发送给 a页面",
};
e.source.postMessage(JSON.stringify(data), e.origin);
});
</script>
</body>
</html>