localstorage跨域&&跨浏览器

2021-08-10  本文已影响0人  bounsail

localstorage无法跨域(同源策略的限制),无法跨浏览器;

localstorage可通过storage event数据变化监听;

window.addEventListener('storage', function(e) {
        if (e.key === 'href') {
            setTargetWin();
        }
}, false);

localstorage实现跨浏览器解决方案:

必须通过flash实现跨浏览器 ,因为不同的浏览器使用的flash都是同一个。因此,使用flash cookie就可以实现这样的功能;

localstorage实现跨域解决方案:

postMessage+iframe 实现跨域的数据读取。

postMessage(data,origin)方法允许来自不同源的脚本采用异步方式进行通信,可以实现跨文本档、多窗口、跨域消息传递。接受两个参数:

【解决思路】

通过postMessage 向【其他域】发送跨域消息;
window.parent.postMessage()
iframe.contentWindow.postMessage()
监听跨域消息 window.addEventListener('message', fn );

【test1域下】 http://www.test1.com/index_a.html

<body>
    <h2>Status</h2>
    <p></p>
    <a href="http://www.test2.com/index_b.html">去index_b查看结果</a>
    <iframe src="http://www.test2.com/getmessage.html" frameborder="0"></iframe>
    <script>
        window.onload = function(){    //在页面加载完成后主页面向iframe发送请求
            window.frames[0].postMessage('jogging, reading and writing','http://www.test2.com');
        }
        window.addEventListener('message', function(e){    // 主页面监听message事件,
            var data = e.data;
            document.querySelector('p').innerHTML = data;
        }, false);
    </script>
</body>

【test2域下】 http://www.test2.com/getmessage.html

<body>
    <script>
        window.addEventListener('message', function(e) {    //iframe接收消息,并把当前颜色发送给主页面  
            if (e.source != window.parent)   
                return;  
            console.log(e.data);
            localStorage.setItem('task',e.data);
            window.parent.postMessage('finished', '*');  
        }, false);
    </script>
</body>

【test2域下】http://www.test2.com/index_b.html

<body>
    <div>点击获取任务</div>
    <p></p>
    <script>
        document.querySelector('div').addEventListener('click', function(){
            document.querySelector('p').innerHTML = localStorage.getItem('task');
        }, false);
    </script>
</body>
上一篇 下一篇

猜你喜欢

热点阅读