当前位置:   article > 正文

localstorage跨域问题_localstorage跨域读取

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>
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号