美文网首页收藏
不同域名之间共享localStorage/sessionStor

不同域名之间共享localStorage/sessionStor

作者: wlchn | 来源:发表于2019-10-17 17:20 被阅读0次

    问题

    两个不同的域名的localStorage不能直接互相访问。那么如何在aaa.com中如何调用bbb.com的localStorage?

    实现原理

    1.在aaa.com的页面中,在页面中嵌入一个src为bbb.comiframe,此时这个iframe里可以调用bbb.com的localStorage。
    2.用postMessage方法实现页面与iframe之间的通信。
    综合1、2便可以实现aaa.com中调用bbb.com的localStorage。

    优化iframe

    我们可以在bbb.com中写一个专门负责共享localStorage的页面,例如叫做page1.html,这样可以防止无用的资源加载到iframe中。

    示例

    以在aaa.com中读取bbb.com中的localStorage的item1为例,写同理:
    bbb.compage1.html,监听aaa.com通过postMessage传来的信息,读取localStorage,然后再使用postMessage方法传给aaa.com的接收者。

    <!DOCTYPE html>
    <html lang="en-US">
    <head>
    <script type="text/javascript">  
        window.addEventListener('message', function(event) {
            if (event.origin === 'https://aaa.com') {
              const { key } = event.data;
              const value = localStorage.getItem(key);
              event.source.postMessage({wallets: wallets}, event.origin);
            }
        }, false);
    </script>
    </head>
    <body>
      This page is for sharing localstorage.
    </body>
    </html>
    

    aaa.com的页面中加入一个src为bbb.com/page1.html隐藏的iframe

    <iframe id="bbb-iframe" src="https://bbb.com/page1.html" style="display:none;"></iframe>
    

    aaa.com的页面中加入下面script标签。在页面加载完毕时通过postMessage告诉iframe中监听者,读取item1。监听bbb.com传回的item1的值并输出。

    <script type="text/javascript">  
      window.onload = function() {  
          const bbbIframe = document.getElementById('bbb-iframe');
          bbbIframe.contentWindow.postMessage({key: 'item1'}, 'https://bbb.com');
      }
      window.addEventListener('message', function(event) {
          if (event.origin === 'https://bbb.com') {
              console.log(event.data);
          }
      }, false);
    </script>
    

    相关文章

      网友评论

        本文标题:不同域名之间共享localStorage/sessionStor

        本文链接:https://www.haomeiwen.com/subject/jpdvmctx.html