在 Web 開發中,如何在兩個獨立的 HTML 頁面之間傳遞數據是一個常見需求。無論是從列表頁跳轉到詳情頁,還是跨頁面共享用戶狀態,掌握多種傳值方式至關重要。本文將系統梳理主流方案,並針對常見問題提供實戰代碼。
| 方式 | 適用場景 | 持久性 | 容量限制 | 跨域支持 |
|---|---|---|---|---|
| URL 參數 (Query String) | 簡單、非敏感數據跳轉 | 會話級 | 約 2KB | 支持 |
| localStorage | 長期保存、較大數據量 | 永久 (手動清除) | 約 5MB | 同源策略限制 |
| sessionStorage | 會話級臨時數據 | 標籤頁關閉即銷毀 | 約 5MB | 同源策略限制 |
| Cookie | 需後端讀取、跨子域共享 | 可設置過期時間 | 約 4KB | 可配置跨域 |
| postMessage API | 跨域 iframe/窗口通信 | 即時、不持久化 | 無明確限制 | 完美支持跨域 |
這是現代瀏覽器原生提供的鍵值存儲 API,操作簡單、容量大,非常適合前端頁面間傳遞結構化數據。
// 將對象序列化為 JSON 字符串存入
const userData = { id: "001", name: "張三", roles: ["admin", "editor"] };
localStorage.setItem("userProfile", JSON.stringify(userData));
// 或使用 sessionStorage (僅當前會話有效)
// sessionStorage.setItem("userProfile", JSON.stringify(userData));
// 取出並反序列化
const raw = localStorage.getItem("userProfile");
if (raw) {
const userData = JSON.parse(raw);
console.log(userData.name); // "張三"
console.log(userData.roles); // ["admin", "editor"]
}
注意: 存儲的值必須是字符串,複雜對象需先JSON.stringify(),讀取後再JSON.parse()。若數據包含循環引用,需先處理或使用第三方庫 (如 flatted)。
在跳轉鏈接上拼接參數:pageB.html?id=123&name=abc。頁面 B 通過 new URLSearchParams(window.location.search) 解析。缺點是長度受限、不適用於敏感信息、且需手動編解碼。
若頁面 A 嵌入頁面 B (iframe) 或彈出新窗口 (window.open),且涉及跨域,postMessage 是唯一安全標準方案。
const targetWindow = document.getElementById('myIframe').contentWindow;
// 或 const targetWindow = window.open('pageB.html');
targetWindow.postMessage({ type: 'INIT_DATA', payload: { token: 'abc123' } }, 'https://target-domain.com');
window.addEventListener('message', (event) => {
// 安全驗證來源
if (event.origin !== 'https://source-domain.com') return;
if (event.data.type === 'INIT_DATA') {
console.log('收到數據:', event.data.payload);
}
});
name=[],[],[] 怎麼辦?JSON.stringify 序列化後存入 localStorage,或確保後端接口返回標準 JSON 格式。storage 事件:window.addEventListener('storage', e => { if(e.key==='userProfile') location.reload(); })。HttpOnly; Secure; SameSite 的 Cookie。postMessage 並嚴格驗證 event.origin。StorageUtil 工具類,統一異常捕獲、序列化、版本遷移邏輯。掌握這些方案,即可靈活應對各類頁面間數據傳遞需求,構建健壯的前端應用。