利用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按鈕測試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM