Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Localstorage in HTML5

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Localstorage in HTML5". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Localstorage in HTML5".

What is localstorage?

A few days ago, I found it strange to operate on cookie in an old project. I consulted to cache some information to avoid passing parameters on URL, but did not consider what problems cookie would bring:

The size of ① cookie is limited to about 4k and is not suitable for storing business data.

② cookie is sent with HTTP transactions every time, wasting bandwidth

We are working on mobile projects, so the technology that is really suitable for use here is that localstorage,localstorage can be said to be an optimization of cookie, which makes it easy to store data on the client side and will not be transferred with HTTP, but it is not without problems:

The size of ① localstorage is limited to about 5 million characters, which varies from browser to browser.

② localstorage is not readable in privacy mode

③ localstorage is essentially reading and writing files, and if there is a lot of data, it will be stuck (firefox will import the data into memory at once, which is scary when you think about it)

④ localstorage cannot be crawled by crawlers. Do not use it to completely replace URL parameters.

All of the above problems can be avoided, so we should focus on how to use localstorage and how to use it correctly.

The use of localstorage

Basic knowledge

There are two types of localstorage storage objects:

① sessionStrage: session means conversation. Session here means that when a user visits a website, the validity period of the session object is only this long during the period from entering the site to closing the site.

② localStorage: save the data on the client hardware device, whatever it is, which means the data will still be there the next time you turn on the computer.

The difference between the two is that one is kept temporarily and the other is preserved for a long time.

Here is a simple code to illustrate its basic use:

XML/HTML Code copies content to the clipboard

SessionStorage

LocalStorage

Read data

Var msg = document.getElementById ('msg')

Text = document.getElementById ('text')

Type = document.getElementById ('type')

Function save () {

Var str = text.value

Var t = type.value

If (t = = 'session') {

SessionStorage.setItem ('msg', str)

} else {

LocalStorage.setItem ('msg', str)

}

}

Function load () {

Var t = type.value

If (t = = 'session') {

MSG [XSS _ clean] = sessionStorage.getItem ('msg')

} else {

MSG [XSS _ clean] = localStorage.getItem ('msg')

}

}

Real scene

In practice, the use of localstorage generally has the following requirements:

① caches general information, such as the departure city of the search page, reaches the city, and does not locate information in real time.

② caches city list data, which tends to be large

Each piece of cached information in ③ needs to be tracked. For example, when the server notifies the city data update, it is automatically set to expire on the last visit.

Each piece of information in ④ has an expiration date status, and the server needs to pull the data outside the expiration date.

XML/HTML Code copies content to the clipboard

Define ([], function () {

Var Storage = _ .inherit ({

/ / default attribute

Propertys: function () {

/ / proxy object. Default is localstorage.

This.sProxy = window.localStorage

/ / 60 * 60 * 24 * 30 * 1000 ms = = 30 days

This.defaultLifeTime = 2592000000

/ / Local cache is used to store the mapping of all localstorage key values to expiration dates.

This.keyCache = 'SYSTEM_KEY_TIMEOUT_MAP'

/ / when the cache capacity is full, the number of caches deleted each time

This.removeNum = 5

}

Assert: function () {

If (this.sProxy = null) {

Throw 'not override sProxy property'

}

}

Initialize: function (opts) {

This.propertys ()

This.assert ()

}

/ *

New localstorage

Data format includes unique key value, json string, expiration date, deposit date

Sign is the formatted request parameter, which is used to return new data for different parameters of the same request. For example, if the list is Beijing, and then it is switched to Shanghai, the cached data will be updated according to different tag. Tag is equivalent to a signature.

Each key value caches only one piece of information.

, /

Set: function (key, value, timeout, sign) {

Var _ d = new Date ()

/ / date of deposit

Var indate = _ d.getTime ()

/ / the final saved data

Var entity = null

If (! timeout) {

_ d.setTime (_ d.getTime () + this.defaultLifeTime)

Timeout = _ d.getTime ()

}

/ /

This.setKeyCache (key, timeout)

Entity = this.buildStorageObj (value, indate, timeout, sign)

Try {

This.sProxy.setItem (key, JSON.stringify (entity))

Return true

} catch (e) {

/ / when the localstorage is full, clear it all

If (e.name = = 'QuotaExceededError') {

/ / this.sProxy.clear ()

/ / when the localstorage is full, choose to delete the data closest to the expiration time, which will have some impact, but it feels better than clearing it all. If there are too many caches, this process is more time-consuming, within the 100ms.

If (! this.removeLastCache ()) throw 'data storage capacity is too large'

This.set (key, value, timeout, sign)

}

Console & & console.log (e)

}

Return false

}

/ / Delete expired cache

RemoveOverdueCache: function () {

Var tmpObj = null, I, len

Var now = new Date () .getTime ()

/ / take out key-value pairs

Var cacheStr = this.sProxy.getItem (this.keyCache)

Var cacheMap = []

Var newMap = []

If (! cacheStr) {

Return

}

CacheMap = JSON.parse (cacheStr)

For (I = 0, len = cacheMap.length; I < len; iTunes +) {

TmpObj = cacheMap [I]

If (tmpObj.timeout < now) {

This.sProxy.removeItem (tmpObj.key)

} else {

NewMap.push (tmpObj)

}

}

This.sProxy.setItem (this.keyCache, JSON.stringify (newMap))

}

RemoveLastCache: function () {

Var i, len

Var num = this.removeNum | | 5

/ / take out key-value pairs

Var cacheStr = this.sProxy.getItem (this.keyCache)

Var cacheMap = []

Var delMap = []

/ / indicates that the storage is too large

If (! cacheStr) return false

CacheMap.sort (function (a, b) {

Return a.timeout-b.timeout

});

/ / what data has been deleted

DelMap = cacheMap.splice (0, num)

For (I = 0, len = delMap.length; I < len; iTunes +) {

This.sProxy.removeItem (delMap [I] .key)

}

This.sProxy.setItem (this.keyCache, JSON.stringify (cacheMap))

Return true

}

SetKeyCache: function (key, timeout) {

If (! key | |! timeout | | timeout < new Date (). GetTime ()) return

Var i, len, tmpObj

/ / get the key value string that is currently cached

Var oldstr = this.sProxy.getItem (this.keyCache)

Var oldMap = []

/ / whether the current key already exists

Var flag = false

Var obj = {}

Obj.key = key

Obj.timeout = timeout

If (oldstr) {

OldMap = JSON.parse (oldstr)

If (! _ .isArray (oldMap)) oldMap = []

}

For (I = 0, len = oldMap.length; I < len; iTunes +) {

TmpObj = oldMap [I]

If (tmpObj.key = = key) {

OldMap [I] = obj

Flag = true

Break

}

}

If (! flag) oldMap.push (obj)

/ / finally put the new array in the cache

This.sProxy.setItem (this.keyCache, JSON.stringify (oldMap))

}

BuildStorageObj: function (value, indate, timeout, sign) {

Var obj = {

Value: value

Timeout: timeout

Sign: sign

Indate: indate

}

Return obj

}

Get: function (key, sign) {

Var result, now = new Date (). GetTime ()

Try {

Result = this.sProxy.getItem (key)

If (! result) return null

Result = JSON.parse (result)

/ / data expires

If (result.timeout < now) return null

/ / signature verification is required

If (sign) {

If (sign = result.sign)

Return result.value

Return null

} else {

Return result.value

}

} catch (e) {

Console & & console.log (e)

}

Return null

}

/ / obtain signature

GetSign: function (key) {

Var result, sign = null

Try {

Result = this.sProxy.getItem (key)

If (result) {

Result = JSON.parse (result)

Sign = result & & result.sign

}

} catch (e) {

Console & & console.log (e)

}

Return sign

}

Remove: function (key) {

Return this.sProxy.removeItem (key)

}

Clear: function () {

This.sProxy.clear ()

}

});

Storage.getInstance = function () {

If (this.instance) {

Return this.instance

} else {

Return this.instance = new this ()

}

}

Return Storage

});

This code contains the basic operation of localstorage, and deals with the above problems, but the real use needs to be abstracted:

XML/HTML Code copies content to the clipboard

Define (['AbstractStorage'], function (AbstractStorage) {

Var Store = _ .inherit ({

/ / default attribute

Propertys: function () {

/ / each object must have a storage key and cannot be repeated.

This.key = null

/ / defaults to the life cycle of a piece of data. S is seconds, M is minutes, and D is days.

This.lifeTime = '30m'

/ / data is returned by default

/ / this.defaultData = null

/ / proxy object, localstorage object

This.sProxy = new AbstractStorage ()

}

SetOption: function (options) {

Extend (this, options)

}

Assert: function () {

If (this.key = null) {

Throw 'not override key property'

}

If (this.sProxy = null) {

Throw 'not override sProxy property'

}

}

Initialize: function (opts) {

This.propertys ()

This.setOption (opts)

This.assert ()

}

_ getLifeTime: function () {

Var timeout = 0

Var str = this.lifeTime

Var unit = str.charAt (str.length-1)

Var num = str.substring (0, str.length-1)

Var Map = {

D: 86400

H: 3600

M: 60

S: 1

}

If (typeof unit = = 'string') {

Unitunit = unit.toUpperCase ()

}

Timeout = num

If (unit) timeout = Map [unit]

/ / in milliseconds

Return num * timeout * 1000

}

/ / caching data

Set: function (value, sign) {

/ / get the expiration time

Var timeout = new Date ()

Timeout.setTime (timeout.getTime () + this._getLifeTime ())

This.sProxy.set (this.key, value, timeout.getTime (), sign)

}

/ / set a single property

SetAttr: function (name, value, sign) {

Var key, obj

If (_ .isObject (name)) {

For (key in name) {

If (name.hasOwnProperty (key)) this.setAttr (k, name [k], value)

}

Return

}

If (! sign) sign = this.getSign ()

/ / get the current object

Obj = this.get (sign) | | {}

If (! obj) return

Obj [name] = value

This.set (obj, sign)

}

GetSign: function () {

Return this.sProxy.getSign (this.key)

}

Remove: function () {

This.sProxy.remove (this.key)

}

RemoveAttr: function (attrName) {

Var obj = this.get () | | {}

If (obj [attrName]) {

Delete obj [attrName]

}

This.set (obj)

}

Get: function (sign) {

Var result = [], isEmpty = true, a

Var obj = this.sProxy.get (this.key, sign)

Var type = typeof obj

Var o = {'string': true,' number': true, 'boolean': true}

If (o [type]) return obj

If (_ .isArray (obj)) {

For (var I = 0, len = obj.length; I < len; iTunes +) {

Result [I] = obj [I]

}

} else if (_ .isObject (obj)) {

Result = obj

}

For (an in result) {

IsEmpty = false

Break

}

Return! isEmpty? Result: null

}

GetAttr: function (attrName, tag) {

Var obj = this.get (tag)

Var attrVal = null

If (obj) {

AttrVal = obj [attrName]

}

Return attrVal

}

});

Store.getInstance = function () {

If (this.instance) {

Return this.instance

} else {

Return this.instance = new this ()

}

}

Return Store

});

When we actually use it, we use the class store to operate localstorage, and the code ends a simple test:

201579150514318.jpg (488 × 184)

The storage is complete, and the request will not be left in the future, so today's code is basically over. Finally, there is a back button in android Hybrid. Once this button is pressed, it will return to the previous page. At this time, the localstorage in it may be invalid! A simple and unreliable solution is to add to webapp:

XML/HTML Code copies content to the clipboard

_ window.onunload = function () {}; / / suitable for single-page applications

Thank you for your reading, the above is the content of "how to use Localstorage in HTML5". After the study of this article, I believe you have a deeper understanding of how to use Localstorage in HTML5, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report