Js跨一级域名同步cookie


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,同步结束


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM