You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中向新窗口安全传递敏感数据?

兼容桌面与移动端的敏感Token传递方案

方案一:使用postMessage API(推荐,安全且兼容)

postMessage是HTML5标准的跨窗口通信API,支持所有现代桌面和移动端浏览器,数据仅在内存中传递,不会存入浏览器存储或URL,安全性高。

父窗口代码:

const newWindow = window.open(url, "MyAppTitle", "width=300, height=600, menubar=no, scrollbars=no, resizable=no");

// 等待子窗口加载完成后发送token
newWindow.addEventListener('load', () => {
  // 替换为你的实际域名,限制消息接收方,防止恶意拦截
  newWindow.postMessage({ token: "mytoken" }, "https://your-domain.com");
});

子窗口代码:

window.addEventListener('message', (event) => {
  // 严格验证消息来源,仅处理可信域名的消息
  if (event.origin !== "https://your-domain.com") return;
  
  const retrievedToken = event.data.token;
  // 此处执行token相关的业务逻辑
});

关键注意事项:必须验证event.origin,确保消息来自可信的父窗口,避免跨站脚本攻击(XSS)。若父窗口和子窗口同源,event.origin会与当前域名一致,严格匹配可大幅提升安全性。


方案二:使用sessionStorage(次选,安全性优于localStorage)

sessionStorage是会话级存储,仅在当前浏览器会话有效,窗口关闭后自动清除,不会持久化到磁盘,风险远低于localStorage。

父窗口代码:

sessionStorage.setItem("tokenString", "mytoken");
const newWindow = window.open(url, "MyAppTitle", "width=300, height=600, menubar=no, scrollbars=no, resizable=no");

子窗口代码:

const retrievedToken = sessionStorage.getItem("tokenString");
// 立即删除token,缩短存储时间
sessionStorage.removeItem("tokenString");
// 后续业务逻辑处理

为什么之前的方案在移动端失效?

部分移动端浏览器(如iOS Safari)因隐私安全限制,会阻断窗口间的直接属性访问(如newWindow.tokenString或window.opener.tokenString),这类非标准的窗口属性传递方式兼容性差,不推荐使用。而postMessage是浏览器规范明确支持的跨窗口通信方式,不存在此类兼容性问题。

内容的提问来源于stack exchange,提问作者D. Verner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 22:47:46