如何在不使用sessionStorage或localStorage的情况下在JavaScript中传递数组到另一页面
嘿,这个问题我之前帮不少开发者解决过,不用sessionStorage或localStorage的话其实有几种靠谱的方案,我给你拆解一下,每种都附上代码示例和适用场景,你可以按需选择:
1. 通过URL查询参数传递
这是最直接的方案,适合小型、非敏感的数组。核心思路是把数组转成JSON字符串,拼到目标页面的URL里,另一个页面再解析这个参数。
发送页面代码:
// 假设我们要传递的数组 const myArray = [1, 2, "hello", { key: "value" }]; // 转成JSON字符串并编码(避免特殊字符问题) const encodedArray = encodeURIComponent(JSON.stringify(myArray)); // 跳转到目标页面,带上参数 window.location.href = `target.html?data=${encodedArray}`;
接收页面代码:
// 获取URL中的查询参数 const urlParams = new URLSearchParams(window.location.search); const encodedData = urlParams.get('data'); // 解码并转成数组 const receivedArray = JSON.parse(decodeURIComponent(encodedData)); console.log(receivedArray); // 输出 [1, 2, "hello", { key: "value" }]
⚠️ 注意:URL有长度限制(不同浏览器略有差异,一般在2KB-8KB之间),如果数组太大或者包含大量字符,可能会被截断,而且参数会暴露在地址栏,敏感数据别用这个方法。
2. 利用Cookie传递
Cookie也是一种可选方案,同样适合小型数组(单个Cookie最大约4KB),可以跨页面共享(只要符合域名路径规则)。
发送页面代码:
const myArray = [1, 2, "hello"]; // 转成JSON字符串,设置Cookie(这里设置有效期为1天,路径为根目录确保所有页面都能访问) document.cookie = `arrayData=${encodeURIComponent(JSON.stringify(myArray))}; expires=${new Date(Date.now() + 86400000).toUTCString()}; path=/`; // 跳转到目标页面 window.location.href = "target.html";
接收页面代码:
// 解析Cookie,找到我们需要的字段 function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } const encodedData = getCookie('arrayData'); const receivedArray = JSON.parse(decodeURIComponent(encodedData)); console.log(receivedArray); // 输出 [1, 2, "hello"]
⚠️ 注意:Cookie大小有限,而且会随每个HTTP请求发送到服务器,不适合大数据;另外如果需要存储敏感数据,记得开启secure和HttpOnly属性(不过HttpOnly的话前端就没法读取了,得后端处理)。
3. 借助服务器端会话存储
如果数组比较大或者包含敏感数据,最好的方式是把数据存在服务器端的会话中,比如用Session(常见于Node.js/Express、PHP、Java等后端框架)。
示例(Node.js + Express + express-session):
发送页面(前端):
const myArray = [1, 2, 3, 4, 5]; // 发送POST请求把数组传给服务器 fetch('/save-array', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ array: myArray }), }) .then(response => response.json()) .then(data => { // 跳转目标页面 window.location.href = "target.html"; });
服务器端(Express):
const express = require('express'); const session = require('express-session'); const app = express(); // 配置session(生产环境要换成更安全的存储,比如Redis) app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true, cookie: { secure: false } // 生产环境建议设为true(HTTPS下) })); app.use(express.json()); // 接收数组并存到session app.post('/save-array', (req, res) => { req.session.userArray = req.body.array; res.json({ success: true }); }); // 目标页面的接口,返回session中的数组 app.get('/get-array', (req, res) => { res.json({ array: req.session.userArray }); }); app.listen(3000, () => console.log('Server running on port 3000'));
接收页面(前端):
// 请求服务器获取session中的数组 fetch('/get-array') .then(response => response.json()) .then(data => { const receivedArray = data.array; console.log(receivedArray); // 输出 [1, 2, 3, 4, 5] });
这个方案的优点是数据存在服务器端,不会暴露在前端,也没有大小限制(只要服务器存储够),适合敏感数据或大数据组。
4. 利用窗口间的直接引用(适用于弹窗/iframe场景)
如果是通过window.open()打开的新页面,或者目标页面是当前页面的iframe,那么可以直接通过窗口对象引用传递数组(前提是同源)。
示例:弹窗场景
父页面代码:
const myArray = [1, 2, "hello"]; // 打开弹窗 const popupWindow = window.open('target.html'); // 等待弹窗加载完成后传递数据(或者在弹窗的onload事件里处理) popupWindow.onload = () => { popupWindow.receivedArray = myArray; };
弹窗页面代码:
// 直接访问父页面传递的变量 console.log(window.receivedArray); // 输出 [1, 2, "hello"]
示例:iframe场景
父页面代码:
<iframe id="myIframe" src="target.html"></iframe> <script> const myArray = [1, 2, "hello"]; const iframe = document.getElementById('myIframe'); iframe.onload = () => { iframe.contentWindow.receivedArray = myArray; }; </script>
iframe页面代码:
console.log(window.receivedArray); // 输出 [1, 2, "hello"]
⚠️ 注意:必须是同源(协议、域名、端口都一致),否则会有跨域限制;而且这种方式只适用于页面有直接关联的场景(弹窗、iframe)。
总结一下:
- 小数据、非敏感:用URL参数或Cookie
- 大数据、敏感数据:用服务器端Session
- 弹窗/iframe场景:用窗口直接引用
内容的提问来源于stack exchange,提问作者mo0n

