前端跨域解决方案(9):location.hash

1 location.hash 核心

location.hash 是 URL 中的锚点(如#section),它有两个关键特性:

  1. 跨域可见:在 A 域名页面中,可通过 iframe 加载 B 域名页面,并修改其 location.hash

  2. 不影响页面:修改 hash 不会触发页面刷新,也不会将数据发送到服务器。

这使得 location.hash 成为跨域通信的一种轻量级方式:通过 iframe 加载跨域页面,利用location.hash 传递数据。location.hash 跨域的核心流程如下:

  1. 主页面加载跨域 iframe:http://b.com的页面;

  2. 跨域 iframe 修改父页面的 location.hash,将数据存入hash

  3. 主页面监听 hashchange 事件:获取跨域数据。

2 实战案例

2.1 服务端A(servera.js)

// 引入 Express 框架
const express = require('express');
// 创建一个 Express 应用
const app = express();
// 设置静态文件夹
app.use(express.static('public'));
// 定义监听端口
const port = 3000;
// 让应用监听在指定端口并在控制台输出信息
app.listen(port, () => {
    // 当服务器开始运行时,打印一条消息
    console.log(`Server is running on http://localhost:${port}`);
});

2.2 服务端B(serverb.js)

// 引入 Express 框架
const express = require('express');
// 创建一个 Express 应用
const app = express();
// 设置静态文件夹
app.use(express.static('public'));
// 定义监听端口
const port =4000;
// 让应用监听在指定端口并在控制台输出信息
app.listen(port, () => {
    // 当服务器开始运行时,打印一条消息
    console.log(`Server is running on http://localhost:${port}`);
});

2.3 主页面(a1.html)




    
    
    origin



    
    

2.4 跨域 iframe 页面(b.html)





    
    
    origin



    


2.5 同域中转页面(a2.html)





    
    
    origin



    

location.hash 跨域通信作为一种纯前端实现方式,无需服务器额外配置,且在所有主流浏览器中兼容性良好,其传递的数据还能通过URL进行分享,方便用户间的信息交互。然而,它也存在明显短板,比如受限于 hash 长度,通常能传递的数据不超过2000字符,且需要借助 iframe 中转,流程相对复杂,仅支持字符串数据,遇到复杂对象时还得进行序列化处理。因此,location.hash 跨域更适合小数据量、单向传输的场景,像跨域传递页面ID、配置标识等简单参数,或是应用于 Vue Router 的 hash 模式这类跨域场景。

下一章将介绍 document.domain 方案 ,敬请期待!

你可能感兴趣的:(前端跨域解决方案汇总,前端,javascript)