如何实现跨域cookie共享

分类: 假的网站365怎么看 时间: 2025-09-17 05:03:34 作者: admin 阅读: 9240

一、 背景

为什么需要实现跨域共享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 }

相关文章

365bet客户端下载

金立w900手机

假的网站365怎么看

央妈主持白岩松:曾暴瘦50斤、抑郁到想轻生,如今57岁满头白发

365bet客户端下载

12伏电瓶充满电电压是多少电流是多少?