跳到主要内容

location.hash 跨域方案

准备


通过koa-static搭建页面服务

  1. 安装koakoa-static依赖

    yarn add koa koa-static -S
  2. 编写koa页面服务

    3000 服务
    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 页面服务启动成功!");
    });
    4000 服务
    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(4000,function(){
    console.log("c 页面服务启动成功!");
    });

语法


a 页面

a页面b页面localhost:3000环境下。a页面加载了c页面,如果a 页面访问c 页面数据会发生跨域,所以需要通过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>a 页面</title>
</head>
<body>
<iframe src="http://localhost:4000/c.html#0928" id="iframe"></iframe>
<script>
window.addEventListener("hashchange",function(){
console.log(location.hash);
});
</script>
</body>
</html>

b 页面

a页面b页面localhost:3000环境下。a页面加载了c页面,如果a 页面访问c 页面数据会发生跨域,所以需要通过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>B页面</title>
</head>
<body>
<script>
window.parent.parent.location.hash = location.hash;
</script>
</body>
</html>

c 页面

c 页面localhost:4000服务环境下

<!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>C 页面</title>
</head>
<body>
<script>
console.log(location.hash);
const iframe = document.createElement("iframe");
iframe.src = "http://localhost:3000/b.html#0928C";
document.body.append(iframe);
</script>
</body>
</html>