localstorage跨域问题

localstorage在泛域名下也存在跨域问题,要想解决这个问题可以通过postmessage。以登录为例,登录后获取的用户信息通过localstorage存储在A.xx.com下,若B.xx.com下的页面需要获取用户信息可以做如下操作:

A.xx.com           存储用户信息到localstorage

<!doctype html>
<html>
    <head>
        <style type="text/css">
            html,body{
                height:100%;
                margin:0px;
            }
        </style>
    </head>
    <body style="height:100%;">
        <script type="text/javascript">
             window.οnlοad=function(){
                var user = JSON.stringify({
                    "uid":window.localStorage.getItem("uid"),
                    "nickname":window.localStorage.getItem("nickname"),
                    "avatar":window.localStorage.getItem("avatar"),
                    "token":window.localStorage.getItem("usertoken")
                });
                window.parent.postMessage(user,'*');
            }
           
        </script>
    </body>

</html>

B.xx.com   向A.xx.com发起消息获取用户信息

<!DOCTYPE html>
<html>
<head>
    <title>Post Message</title>
</head>
<body>
    <div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
        <div id="color">Frame Color</div>
    </div>
    <div>
        <iframe id="child" src="http://A.xx.com"></iframe>//通过iframe发起消息
    </div>


    <script type="text/javascript">
        window.οnlοad=function(){
            window.frames[0].postMessage('getuser','http://A.xx.com');
        }


        window.addEventListener('message',function(e){
            var user= JSON.parse(e.data);

            if(user.uid != null){

                //如果用户信息不为空 时逻辑               

                ...

            }else{

                //用户信息为空时逻辑

                ...
            }
            
        },false);
    </script>
</body>
</html>
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值