利用iframe跨域写localStorage的范例

{{ time }}

a.com/index_a.html:

<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <title>cross domain</title>
</head>

<body>
    <h2>Status</h2>
    <p></p>
    <a href="http://b.com/index_b.html">去index_b查看结果</a>
    <iframe src="http://b.com/getmessage.html" frameborder="0" style="width:0;height:0;"></iframe>
    <script>
        window.onload = function () {
            //在页面加载完成后主页面向iframe发送请求
            window.frames[0].postMessage('跨域存储', 'http://b.com');
        }

        // 主页面监听message事件,
        window.addEventListener('message', function (e) {
            var data = e.data;
            document.querySelector('p').innerHTML = data;
        }, false);
    </script>
</body>

</html>

b.com/getmessage.html:

<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <title>getmessage</title>
</head>

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

            window.parent.postMessage('finished', '*');
        }, false);
    </script>
</body>

</html>

b.com/index_b.html:

<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

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

</html>

借此思想可实现跨域登录

参考文献:

https://www.jianshu.com/p/e86d92aeae69/