js頁面間通信方法實現


  在寫頁面的時候經常會碰到這樣的需求:需要兩個打開着的頁面間傳遞數據或者事件。

  比如:已有列表頁A,通過A打開詳情B進行編輯;編輯保存之后希望A能自動刷新頁面。這個時候就可以用到“storage”事件。關於localStorage的用法可在其他地方找到。

  可觸發“storage”事件的條件如下:

  同一個瀏覽器打開了多個同源的頁面(URL由協議、域名、端口和路徑組成,如果兩個URL的協議、域名和端口相同,則表示他們同源);

  一個網頁中修改localStorage

  另一個網頁注冊了storage事件

http://www.cnblogs.cn/demo/index.html

//這個網址,協議是http://域名是www.cnblogs.cn,端口是80(默認端口可以省略)


//對比URL:

http://www.cnblogs.cn/demo2/other.html     //同源

http://www.cnblogs.cn:81/demo/index.html   //不同源

http://sxh.cnblogs.cn/demo/index.html      //不同源

http://www.pudn.cn/demo/index.html         //不同源

  在測試的時候,一定要保證是同源頁面。

  下面是頁面間交互代碼,實現非常簡單,pageA和pageB之間通信。

pageA:添加“storage”監聽

<!DOCTYPE html>

<html>

<head>

    <title>page A</title>

</head>

<body>

<script>

    window.addEventListener("storage", function (e) {

        console.log(e)

        console.log(e.newValue)

    });

</script>

</body>

</html>

pageB:設置localStorage

<!DOCTYPE html>

<html>

<head>

<title>page B</title>

</head>

<body>

<button>click<button>

</body>

<script>

      document.querySelector('button').onclick = function(){
        //留意random,若Refresh的值未做變更,則不會觸發A頁面的“storage”事件
              localStorage.setItem('Refresh', Math.random()*10);

      }

</script>

</html>

 

  


免責聲明!

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



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