问题

两个不同的域名的 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>