JS页面跳转传值:URL参数、Storage与postMessage方案对比

作者:交互手记时间:2026-12-01浏览:671

页面跳转传值优先用 URL 参数,适合少量数据;跨域或复杂对象用 postMessage ;同域且需持久化用 localStorage 。

JS页面跳转传值:URL参数、Storage与postMessage方案对比

URL 参数传递与解析

通过修改 window.location.href 或 ?key=value 实现跳转,目标页使用 URLSearchParams 解析。

JS页面跳转传值:URL参数、Storage与postMessage方案对比

URL 参数限制长度且明文可见,适合 ID、状态码等简单数据。注意特殊字符编码,避免中文乱码。

Storage 持久化方案

在源页写入 localStorage.setItem(),目标页读取后清除,适合大对象或敏感数据(需自行加密)。

JS页面跳转传值:URL参数、Storage与postMessage方案对比

// source.html
function jumpWithParams() {
    const data = { id: 123, name: 'test' };
    const queryString = new URLSearchParams(data).toString();
    window.location.href = `target.html?${queryString}`;
}

// target.html
const params = new URLSearchParams(window.location.search);
console.log('ID:', params.get('id')); // 输出: ID: 123
console.log('Name:', params.get('name')); // 输出: Name: test

// storage.html (source)
localStorage.setItem('pageData', JSON.stringify({ token: 'abc' }));
window.location.href = 'storage_target.html';

// storage_target.html
const stored = localStorage.getItem('pageData');
if (stored) {
    console.log('Stored Data:', JSON.parse(stored));
    localStorage.removeItem('pageData');
}

URL 参数示例直接输出解析后的 ID 和 Name,适用于简单跳转。Storage 示例演示写入、跳转、读取并清除流程,确保数据不残留。实际使用时根据数据量和安全性选择方案。

Storage 是异步操作但同步生效,需注意同源策略和存储容量限制(通常 5MB)。

postMessage 跨域通信

使用 window.postMessage() 发送消息,目标页监听 message 事件接收,支持跨域和窗口间通信。

需验证 event.origin 确保来源安全,适合 iframe 或不同域名页面间传值。

作者最新文章
相关文章
更多