HTML5之Local Storage

HTML5 STORAGE SUPPORT
IE FIREFOX SAFARI CHROME OPERA IPHONE ANDROID
8.0+ 3.5+ 4.0+ 4.0+ 10.5+ 2.0+ 2.0+

 

Local Storage Detection:javascript

## 方法一
function supports_local_storage() {
try { return 'localStorage' in window && window['localStorage'] !== null; } catch(e){ return false; } }
## 方法二 
if(localStorage && localStorage.getItem('LOCALSTORAGEKEY')){
  // localStorage is available and has the KEY ''LOCALSTORAGEKEY
}
if (Modernizr.localstorage) {
  // localStorage is available!
} else {
  // no native support for local storage :(
  // try a fallback or another third-party solution
}

 

Local Storage Method:java

key:this

e.g: localStorage.key(1)url

 

getItem:spa

e.g: localStorage.getItem('LOCALSTORAGEKEY')localstorage

 

setItem:code

e.g: localStorage.setItem('LOCALSTORAGEKEY', 'LOCALSTORAGEVALUE')對象

 

removeItem:blog

e.g: localStorage.removeItem('LOCALSTORAGEKEY')索引

 

clear:

e.g: localStorage.clear()

 

 

Tracking changes:

if (window.addEventListener) {
  window.addEventListener("storage", handle_storage, false);
} else {
  window.attachEvent("onstorage", handle_storage);
}

function handle_storage(e) {
  if (!e) { e = window.event; }
}

STORAGEEVENT OBJECT:

PROPERTY TYPE DESCRIPTION
key string the named key that was added, removed, or modified
oldValue any the previous value (now overwritten), or null if a new item was added
newValue any the new value, or null if an item was removed
url* string the page which called a method that triggered this change
* Note: the url property was originally called uri. Some browsers shipped with that property before the specification changed. For maximum compatibility, you should check whether the url property exists, and if not, check for the uri property instead.

 

 

注意事項:

一、不推薦使用window.localStorage,可直接使用localStorage,window.localStorage在IE下有可能會拋出錯誤;

二、localStorage是以key=value值對形式存在的,value值一概爲字符串,字面量對象可用JSON.stringify()轉換成字符串後賦值給key;

三、localStorage.getItem('KEY')取出key對應的值後,須要JSON.parse()進行解析,不然其值只是一個看起來像字面量對象的字符串,同⓶;

四、若是經過localStorage.key(num)取值,num的起始索引是0,不推薦;

五、localStorage存儲上限爲5MB,超出會拋出「QUOTA_EXCEEDED_ERR」;

相關文章
相關標籤/搜索