前端localstorage+cookie 解决同主域名跨域传值

5,544 阅读1分钟

业务场景

在同一个主域名下(如aaa.com),不通子域名(b.aaa.com,c.aaa.com)跨域名传递地址,并且需要做到关闭浏览器,再次打开浏览器取出地址。

解决方案

  • 前端能做到浏览器储存常用方法localstorage,这里我们用localstorage进行离线本地存储。
  • 前端能做到浏览器同主域名跨域进行传值的localstoragecookie都可以做到,这里我们选择cookie。(原因:localstorage需要iframe嵌套才能做到,具体方法这里不解释了)

具体方法

利用cookie的domain属性。如果设置为“.aaa.com”,则所有以“aaa.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”。

<script type="text/javascript">  
    function setCookie(c_name,value,expiredays) {  
        var exdate=new Date();  
        exdate.setDate(exdate.getDate()+expiredays);  
        alert(exdate.getDate()+expiredays);  
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";path=/;domain=aaa.com";  
    } 
</script>

实际应用

这里列表页和详情页都是单独工程例item.aaa.com detai.aaa.com

在item.aaa.com中

//选择地址后地址id集合[1,2,3]
let addressArr=[123]
//存储在localStorage中
localStorage.setItem("addressArr",JSON.stringify(addressArr))
//从localStorage中取出存放到cookie中
let newAddressArr =localStorage.getItem('addressArr')
//把地址存储到cookie中
setCookie('addressArr',newAddressArr);
function setCookie(c_name,value,expiredays) {  
        var exdate=new Date();  
        exdate.setDate(exdate.getDate()+expiredays);  
        alert(exdate.getDate()+expiredays);  
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";path=/;domain=aaa.com";  
    } 

在detai.aaa.com中取地址

//从cookie中取出地址
function getCookie(cookieName) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for(var i = 0; i < arrCookie.length; i++){
        var arr = arrCookie[i].split("=");
        if(cookieName == arr[0]){
            return arr[1];
        }
    }
    return "";
}
//取到的地址在页面中应用 addressArr可以直接在页面业务中用到
let addressArr = JSON.parse(getCookie("addressArr"))
//把cookie取出地址存储到localstorage中
localStorage.setItem("addressArr",JSON.stringify(addressArr))

其他

这里是item.aaa.com向detail.aaa.com中地址传值,实现了关闭浏览器,再次打开浏览器上次历史选择地址还存在。

同理:item.aaa.com和detail.aaa.com中互相传值并存储就不介绍了,只是互相用了对方方法。