一、 背景
為什么需要實現跨域共享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 }