zoukankan      html  css  js  c++  java
  • 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,同步结束

  • 相关阅读:
    APP开发收藏的几个网址,APP性能监测
    MAC 安装STF
    更新react 之后 出现 can not find ‘@babel/runtime/helpers/esm/createSuper’ 提示
    react 相关笔记
    jenkins 配置子节点 关键在端口号和下方代理配置
    移动APP测试8点注意事项
    自动部署java项目,热部署方式
    ubuntu搭建elk服务器
    数据库常用操作,sql server; mysql
    windows 关闭端口占用及其他常见操作
  • 原文地址:https://www.cnblogs.com/zhhying/p/4167703.html
Copyright © 2011-2022 走看看