跨子域名Cookie共享问题:仅有权限操作my-project.parent.com
核心思路
由于无法直接设置domain=.parent.com级别的Cookie(需父域名权限或在父域名下写入),可通过跨域消息传递+目标子域名自行写入Cookie的方式实现数据共享,全程仅需操作my-project.parent.com及协调other-project.parent.com做少量配置。
具体实现步骤
在my-project.parent.com中发送共享数据
需要共享数据时,使用postMessage向目标子域名发送结构化数据,同时严格限制目标来源确保安全:// my-project.parent.com 代码示例 const targetOrigin = 'https://other-project.parent.com'; // 携带需共享的键值及过期时间等元信息 const sharedData = { cookieKey: 'user_preference', cookieValue: 'dark_mode', expires: Date.now() + 86400000 // 24小时后过期 }; window.postMessage(sharedData, targetOrigin);在other-project.parent.com中监听并写入Cookie
在目标项目的页面中添加消息监听,验证来源后将收到的数据写入自身子域名的Cookie:// other-project.parent.com 代码示例 window.addEventListener('message', (event) => { // 仅接受可信来源的消息,防止恶意注入 if (event.origin !== 'https://my-project.parent.com') return; const { cookieKey, cookieValue, expires } = event.data; // 写入当前子域名的Cookie,可按需配置path、secure、SameSite等属性 document.cookie = `${cookieKey}=${encodeURIComponent(cookieValue)}; expires=${new Date(expires).toUTCString()}; path=/; secure; SameSite=Lax`; });
关键注意事项
- 安全校验:必须严格验证
event.origin,只处理来自my-project.parent.com的消息,避免跨域攻击风险。 - 数据完整性:建议传递包含过期时间、校验值的结构化数据,方便目标域名规范管理Cookie生命周期。
- 兼容性:
postMessage支持所有现代浏览器,无需额外依赖库。
替代方案(若无法修改other-project代码)
如果无法操作other-project.parent.com的代码,可尝试隐藏iframe中转方案:
- 在
my-project.parent.com中嵌入一个指向other-project.parent.com的隐藏iframe。 - 向iframe发送
postMessage,由iframe在自身域名下写入Cookie。 - 写入完成后,iframe通过
postMessage通知主页面确认操作。
注:此方案要求目标项目未设置X-Frame-Options限制iframe嵌入,且需目标域名页面默认支持消息监听逻辑。
内容的提问来源于stack exchange,提问作者Mohamed Ibrahim
相关产品推荐
相关产品推荐

