h5 storage事件监听
生活随笔
收集整理的這篇文章主要介紹了
h5 storage事件监听
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
分析
引用《h5移動web開發指南》上的話:
“當同源頁面的某個頁面修改了localStorage,其余的同源頁面只要注冊了storage事件,就會觸發”
所以,localStorage的例子運行需要如下條件:
- 同一瀏覽器打開了兩個同源頁面
- 其中一個網頁修改了localStorage
- 另一網頁注冊了storage事件
很容易犯的錯誤是,在同一個網頁修改本地存儲,又在同一個網頁監聽,這樣是沒有效果的。
例子
網頁A:監聽了storage事件:
<!DOCTYPE html> <html> <head lang="en"><title>A</title> </head> <body> <script>window.addEventListener("storage", function (e) {alert(e.newValue);}); </script> </body> </html>網頁B:修改了localStorage
<!DOCTYPE html> <html> <head lang="en"><title>B</title> </head> <body> <script>localStorage.clear();localStorage.setItem('foo', 'bar'); </script> </body> </html>運行 : 將上面兩個網頁保存,放到同一個服務器上,然后,先打開A.html,再打開B.html。就會看到A.html會彈出提示框。注意兩個網頁要同源。
擴展
如果非得要在同一網頁監聽怎么辦?可以重寫localStorage的方法,拋出自定義事件:
<!DOCTYPE html> <html> <head lang="en"><title>A</title> </head> <body> <script>var orignalSetItem = localStorage.setItem;localStorage.setItem = function(key,newValue){var setItemEvent = new Event("setItemEvent");setItemEvent.newValue = newValue;window.dispatchEvent(setItemEvent);orignalSetItem.apply(this,arguments);}window.addEventListener("setItemEvent", function (e) {alert(e.newValue);});localStorage.setItem("nm","1234"); </script> </body> </html>總結
以上是生活随笔為你收集整理的h5 storage事件监听的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言延时跑马灯实验报告,跑马灯实验C语
- 下一篇: 【路径规划】基于NSGA2实现无人机三维