利用iframe实现不同域名间共享localStorage/sessionStorage

概要

在实际开发场景中,有时我们会遇到不同域名下实现状态共享的类似需求,我们知道两个不同的域名的localStorage是不能直接互相访问。那么如何在projectA.com中调用projectB.com的localStorage呢,本文手把手带你实现。

实现原理

  • 1.在projectA.com的页面中,嵌入一个src为projectB.com的iframe,此时这个iframe里可以调用projectB.com的localStorage。
  • 2.用postMessage方法实现页面与iframe之间的通信。

综合1、2便可以实现projectA.com中调用projectB.com的localStorage。

实现demo

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

以在projectA.com中读取projectB.com中的localStorage的token为例。
projectB.com中share.html,监听projectA.com通过postMessage传来的信息,读取localStorage,然后再使用postMessage方法传给projectA.com的接收者。
在localstorage->projectB目录下新建share.html, 在localstorage->projectA目录下新建project-a.html。
在projectA.com的页面中加入一个src为projectB.com/share.html的iframe。
在projectA.com的页面中加入下面script标签。在页面加载完毕时通过postMessage告诉iframe中监听者,读取token。监听projectB.com传回的token的值并输出。
代码如下:

share.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>project B</title>
  <style type="text/css">
    body {
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
      margin: 0 auto;
    }
    h1 {
      width: 100%;
      color: red;
      white-space: nowrap;
    }
  </style>
</head>
<body>
    <h1>This page is for sharing localstorage.</h1>
    <script type="text/javascript">
      localStorage.setItem('token', 'token-value')
      window.addEventListener('message', function (evt) {
        if (evt.origin === 'http://192.168.1.4:8081') {
          console.log("接收到了project A的请求")
          const value = localStorage.getItem('token')
          evt.source.postMessage({token: value}, evt.origin)
        }
      }, false)
    </script>
</body>
</html>

project-a.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>project A</title>
  <style type="text/css">
    body {
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
    }
    iframe {
      width: 100%;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <iframe id="JS_iframe" src="http://192.168.1.4:8080/share.html" frameborder="0"></iframe>
  <button id="JS_button">获取token</button>
  <script type="text/javascript">
    const buttonEl = document.querySelector('#JS_button')
    buttonEl.addEventListener('click', function (evt) {
      const iframeEl = document.querySelector("#JS_iframe")
      iframeEl.contentWindow.postMessage({ auth: 'admin' }, 'http://192.168.1.4:8080/share.html')
    }, false)

    window.onload = function () {
      const iframeEl = document.querySelector("#JS_iframe")
      iframeEl.contentWindow.postMessage({ auth: 'admin' }, 'http://192.168.1.4:8080/share.html')
    }
    
    window.addEventListener('message', function (evt) {
      if (evt.origin === 'http://192.168.1.4:8080') {
        console.log("收到projectB的消息:", evt.data)
      }
    }, false)
  </script>
</body>
</html>

测试demo

全局安装npm install -g http-server,在cmd控制台分别进入projectB和projectA目录运行http-server -c-l启动两个服务。

在浏览器访问,点击获取token按钮测试

posted @ 2022-04-01 22:42  Elwin0204  阅读(4241)  评论(0编辑  收藏  举报