天天看點

html5 storage事件

HTML5 雖然很多年了,但是真的了解不不夠不夠。主題說的是 storage時間,說起對 storage 事件的了解還是從  QQ音樂

 說起。

QQ音樂的首頁是 https://y.qq.com , 而實際播放的頁面是 https://y.qq.com/portal/player.html。你在其他裡面點選播放或者添加的時候,你會發現 https://y.qq.com/portal/player.html 會實時的變化。目前我想,這個神奇啊,

目前想法是如下,可是怎麼想都比較low啊。

1. 存入 localStorage 或者 indexedDB裡面,然後定期讀取呢?

2. socket開啟呢?

3. 中間服務中轉呢?

曾有同僚偶然間提到到storage事件,當時也上心。前兩天無意中看到一篇  

h5 storage事件監聽

 的文章。

順便再去探究一下 QQ音樂。 

html5 storage事件
html5 storage事件
點選播放歌曲的時候,在player.html頁面即播放頁面捕獲的資料。這就完全驗證了 QQ音樂這個添加音樂的實作就是基于 storage事件來完成的。
html5 storage事件
那麼我們先來看一下, storage event的定義   The 

storage

 event
。 簡單就是說 session storage 和 local storage 的值變化的時候,會觸發該事件。

storage

 event is fired on a 

Document

's 

Window

 object when a storage area changes, as described in the previous two sections ( for session storage for local storage

).

When a user agent is to send a storage notification for a 

Document

, the user agent must  queue a task  to  fire an event  named 

storage

 at the 

Document

 object's 

Window

object, using 

StorageEvent

.

怎麼使用呢:

A頁面

window.addEventListener("storage", function (e) {
        console.log(e)
    });      

B 頁面

localStorage.setItem('key1', 'vakue1')      

B頁面執行這段代碼的時候, A頁面就會打出e整個對象。

我們看一下e究竟有哪些屬性或者方法,注意标紅的五個屬性,其實的都是普通事件都有的屬性,

  key: 不用解釋,更新的屬性名

       newValue: 新值

      oldValue : 舊值

      storageArea:  我這裡了解就是localStorage的值

      url: 觸發該事件的網址

html5 storage事件

 這裡有兩點:

1.  當localStorage調用 setItem, removeItem ,clear方法的時候,調用的頁面本身是不會觸發storage事件的。

2. 如果想調用頁面也能監聽localStorage的變化,可以像如下,當然removeItem ,clear方法也得重寫。顯得有點麻煩

var _setItem = localStorage.setItem;
    localStorage.setItem = function(key,newValue){
        var setItemEvent = new Event("setItemEvent");
        setItemEvent.newValue = newValue;
        window.dispatchEvent(setItemEvent);
        _setItem .apply(this,arguments);
    }
    window.addEventListener("setItemEvent", function (e) {
        console.log(e)
    });
    localStorage.setItem("key1","value1");      

當然,我自己也用過另外一種方式

var ls = new Proxy(localStorage, {
            get: function (target, key, receiver) {
                var val = Reflect.get(target, key, receiver)
                return typeof val === 'function' ? val.bind(localStorage) : val
            },
            set: function (target, key, value, receiver) {

                var evt = document.createEvent('StorageEvent');
                evt.initStorageEvent('storage', false, false, key, window.localStorage.getItem(key), value, window.location.href, window.localStorage);
                window.dispatchEvent(evt);

                return Reflect.set(target, key, value , receiver)

            },
            deleteProperty: function (target, key) {

                var evt = document.createEvent('StorageEvent');
                evt.initStorageEvent('storage', false, false, key, window.localStorage.getItem(key), null, window.location.href, window.localStorage);
                window.dispatchEvent(evt)

                Reflect.deleteProperty(target, key)
            }
        })


        window.addEventListener('storage', function (e) {
            console.log(e)
        })

        ls.a = 2
        delete ls.a
      

  

已知的一些問題:

  1. Storing large amounts of data in Safari (on OSX & iOS) can result in freezing the browser  see bug
  2. IE10 in Windows 8 has an issue where localStorage can fail with the error message "SCRIPT5: Access is denied" if "integrity" settings are not set correctly.  see details
  3. Internet Explorer does not support storing most of the ASCII characters with codes under x20.
  4. The "storage" event is completely wrong in IE: 

    IE10 : The storage event is fired even on the originating document where it occurred. Causes problems with multiple windows websites, and huge problems with iframes.

    IE11 : The storage event's oldValue and newValue are identical (newValue is supposed to contain the storage's updated value). 

    Partial workaround: regularly probe the storage's value and compare with the last known value on all pages where you want to listen to this event, and track the last submitted value to determine if the modification was triggered locally.

  5. In IE attempting to access localStorage on HTML files served from the file system results in the localStorage object being 

    undefined

  6. In iOS 5 & 6 localStorage data is stored in a location that may occasionally be cleared out by the OS.
  7. In private browsing mode, Safari and iOS Safari up to including version 10.x as well as the Android browser (not include Chrome for Android) do not support setting sessionStorage or localStorage.
  8. IE 8 and 9 store data based only on hostname, ignoring the scheme (http vs https) and port number as required by the specification.

參考: 

storage

StorageEvent 初試WebStorage之localstorage Can I Use LocalStorage initStorageEvent method

繼續閱讀