html5 storage事件

來源:互聯網
上載者:User

標籤:自己   cti   named   rip   use   key   describe   can   hostname   

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音樂。 

 

點擊播放歌曲的時候,在player.html頁面即播放頁面捕獲的資料。這就完全驗證了 QQ音樂這個添加音樂的實現就是基於 storage事件來完成的。

那麼我們先來看一下, storage event的定義  The storage event。 簡單就是說 session storage 和 local storage 的值變化的時候,會觸發該事件。

The 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 Windowobject, 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: 觸發該事件的網址

 

 這裡有兩點:

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");

 

當然,我自己也用過另外一種方式, 這種方法,遺憾的是, localStorage被代理,導致 ls調用方法都會報錯,導致 ls現在是一個對象了。

        var ls = new Proxy(localStorage, {            get: function (target, key, receiver) {                var val = Reflect.get(target, key, receiver)                return val && JSON.parse(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 && JSON.stringify(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.

 

參考: 

The storage event

StorageEvent

初試WebStorage之localstorage

Can I Use LocalStorage

initStorageEvent method

 

html5 storage事件

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.