document.domain 跨域方案
如果两个页面存在多级域名关系
,那么可以通过document.domain
来实现页面之间的数据共享
准备
-
修改本机
host
文件,模拟多级域名关系host 文件127.0.0.1 a.bolawen.com
127.0.0.1 b.bolawen.com -
通过
koa
、koa-static
搭建本机页面服务const Koa = require("koa");
const Path = require("path");
const Static = require("koa-static");
const app = new Koa();
app.use(Static(Path.resolve(__dirname,'./')));
app.listen(3000,function(){
console.log("a 页面服务启动成功!");
});
语法
a 页面
a 页面 通过 a.bolawen.com:3000/a.html 访问 , a 页面 加载 b 页面,b 页面 地址为b.bolawen.com:3000/b.html,很明显存在跨域问题。那么这时候我们可以通过document.domain来解决跨域
<!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>a 页面</title>
</head>
<body>
<iframe src="http://b.bolawen.com:3000/b.html" id="iframe"></iframe>
<script>
document.domain = "bolawen.com";
const iframe = document.getElementById("iframe");
iframe.addEventListener("load", function () {
console.log(iframe.contentWindow.data);
});
</script>
</body>
</html>
b 页面
b 页面 通过 b.bolawen.com:3000/b.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>B页面</title>
</head>
<body>
<script>
document.domain = "bolawen.com";
var data = {
title:'B 页面'
}
</script>
</body>
</html>