Skip to content

menglexing/crossStorage

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 

Repository files navigation

crossStorage

具有跨域能力的localStorage。(需要浏览器支持 localStorage 和 postMessage)

API

  • setItem(key, val)

    存。val可以是 Boolean、Number、String、Object

  • getItem(key, callback)

    取。以获取到的val作为实参调用callback,val存的时候是什么类型的值,获取到的就是什么类型的值

  • removeItem(key)

    删。

  • clear()

    全删。

  • change(callback)

    监听window.onstorage事件,setItem/removeItem/clear操作会触发storage事件,以{key, oldValue, newValue}作为实参调用callback。

    removeItem时,newValuenull;当clear时,key, oldValue, newValue均为null

Example

crossStorage.setItem('hero', 'annie')
crossStorage.getItem('hero', console.log)    // => 'annie'
/* page A */
crossStorage.setItem('annie', {sex: 0, age: 7, say: 'Did you see my bear?'})

setTimeout(function(){
    crossStorage.setItem('annie', {sex: 0, age: 8, say: 'Did you see my bear?'})
}, 365*24*60*60*1000)

/* page B */
crossStorage.change(function(e){
    if (e.key === 'annie') {
        if (e.newValue.age > e.oldValue.age) {
            console.log('Happy Birthday !')
        }
    }
})

原理

About

具有跨域能力的localStorage

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 67.4%
  • HTML 32.6%