如何实现跨域cookie共享
一、 背景
为什么需要实现跨域共享cookie, 比如追踪用户的身份,根据特定用户进行推送或推荐。
二、 Cookie共享的几种方案
- 通过中间域名,比如a.example.com 和 b.example.com 可通过cookie.example.com 或 *.example.com 来实现cookie共享;
- 通过CORS (cross origin resource sharing)跨域读取cookie, 参考。
- 通过多域写cookie, image tag 方式,在其他域内种植上和当前域相同的cookie
三、 几种方案对比
方案 | 优点 | 缺点 |
中间域名 | 无需前端改造 | 仅适用于二级域名相同的跨域共享。对已经存在的项目如严格依赖当前域名,不能有多次跳转比如a->b->a 是不合适的 |
CORS 读 | 少量的前端适配 | CORS读取后,当前页需要一次自刷新来重新发送cookie |
image tag 写 | 后端无感知 |
前端适配及网络IO (需要从其他域获取cookie信息),页面会有顿挫感, 对写cookie的时机有要求 |
四、 CORS方式读取cookie code snippet
1 function addCrossCookie() { 2 var getCookie = "http://your.cross.domain/get_cookie"; 3 $.ajax({ 4 type: "get", 5 url: getCookie, 6 dataType: "text", 7 mode: "cors", 8 crossDomain: true, 9 xhrFields: { 10 withCredentials: true 11 }, 12 success: function(output) { 13 /* 14 * if cookie existed under `your.cross.domain`, you can answer it back by `output`. 15 * then document.cookie set it to `current.domain` 16 * window.location.reload to trigger a browser tab refresh to take the cross cookie to your backend. 17 */ 18 document.cookie = output; 19 setTimeout(function() { 20 window.location.reload(); 21 }, 0); 22 }, 23 error: function(output) { 24 console.log(output); 25 } 26 }); 27 }
分类:
领域总结
标签:
ajax
, cross cookie sharing
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)