1. 純Js同步兩個域名下的cookie
document.cookie = "name=" + "value;" + "expires=" + "datatime;" + "domain=" + "" + "path=" + "/path" + "; secure";
//name Cookie名字
//value Cookie值
//expires 有效期截至(單位毫秒)
//path 子目錄
//domain 有效域
//secure 是否安全
拿淘寶與天貓舉例,淘寶登錄后跳轉到天貓頁面,天貓頁面有一個iframe,請求任意頁面
<iframe src='http://localhost:14373/test/Index' width='100' height='100' style="display:none"></iframe>
淘寶頁面中js獲取當前頁面的cookie並作為參數跳轉回天貓頁面
window.location = "http://localhost:20272/GetCookie/Index?" + document.cookie;
天貓頁面獲取url中的地址並將cookie寫入本域名下
var url = window.location.toString();//獲取地址 var get = url.substring(url.indexOf("liuph"));//獲取變量和變量值 var idx = get.indexOf("=");//獲取變量名長度 if (idx != -1) { var name = get.substring(0, idx);//獲取變量名 var val = get.substring(idx + 1);//獲取變量值 setCookie(name, val, 1);//創建Cookie }
2. 經過后台處理同步cookie
天貓頁面直接請求淘寶的后台方法
$.ajax({ type: "GET", dataType: 'jsonp', jsonp: 'jsonp_callback', url: 'http://localhost:14373/test/GetString?cookie=?', success: function (da) { alert(da.name + "|" + da.value); }, error: function (){ alert("ERROR"); } });
淘寶后台代碼
public void GetString() { HttpCookie cookie = Request.Cookies["liuph"]; var response = HttpContext.Response; response.ContentType = "text/json"; string str = Request.QueryString["cookie"];//JS接受變量名 response.Write(str + "({\"name\":" + "\"" + cookie.Name + "\"" + ",\"value\":" + "\"" + cookie.Value + "\"})");//返回數據 }
ok,同步結束