在寫頁面的時候有時會遇到這樣的需求,需要兩個頁面之間傳遞數據或者一個事件。這個時候,就需要用到我今天所要講的storage事件,學習這個事件之前,需要先了解localStorage的用法。具體用法可以查看其他文檔。出發storage事件的條件如下:
同一個瀏覽器打開了兩個同源的頁面
一個網頁中修改localStorage
另一網頁注冊了storage
事件
storage事件,只有在同源頁面下,才有作用,不同源是沒有作用的。那么什么是同源呢?
URL由協議、域名、端口和路徑組成,如果兩個URL的協議、域名和端口相同,則表示他們同源。舉個栗子:
http://www.wszdaodao.cn/demo/index.html //這個網址,協議是http://域名是www.wszdaodao.cn,端口是80(默認端口可以省略) //對比URL: http://www.wszdaodao.cn/demo2/other.html //同源 http://www.wszdaodao.cn:81/demo/index.html //不同源 http://sxh.wszdaodao.cn/demo/index.html //不同源 http://www.mamama.cn/demo/index.html //不同源
所以在測試時候,一定要保證是同源頁面。
下面是兩頁面間交互代碼,實現非常簡單,pageA與pageB之間通信。
page A : 設置localStorage
<!DOCTYPE html> <html> <head> <title>page A</title> </head> <body> <button>click<button> </body> <script> document.querySelector('button').onclick = function(){ localStorage.setItem('Num', Math.random()*10); } </script> </html>
page B: 監聽storage事件
<!DOCTYPE html> <html> <head> <title>page B</title> </head> <body> <script> window.addEventListener("storage", function (e) { console.log(e) console.log(e.newValue) }); </script> </body> </html>
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com