the storage of information of web app
来源:互联网 发布:广汽丰田面试经验知乎 编辑:程序博客网 时间:2024/06/05 23:46
a function needed by the project,storage the information of web app.
http://han.guokai.blog.163.com/blog/static/13671827120112694851799/
浏览器本地数据(sessionStorage、localStorage、cookie)与server端数据
2011-03-06 23:48:21| 分类: 默认分类|举报|字号 订阅
详说 Cookie, LocalStorage 与 SessionStorage
最近在找暑期实习,其中百度、网易游戏、阿里的面试都问到一些关于HTML5的东西,问题大多是这样开头的:“你用过什么HTML5的技术呀?” 而后,每次都能扯到 Cookie 和 localStorage 有啥差别。这篇文章就旨在详细地阐述这部分内容,而具体 Web Storage API 的使用可以参考MDN的文档,就不在这篇文章中赘述了。
基本概念
Cookie
Cookie 是小甜饼的意思。顾名思义,cookie 确实非常小,它的大小限制为4KB左右,是网景公司的前雇员 Lou Montulli 在1993年3月的发明。它的主要用途有保存登录信息,比如你登录某个网站市场可以看到“记住密码”,这通常就是通过在 Cookie 中存入一段辨别用户身份的数据来实现的。
localStorage
localStorage 是 HTML5 标准中新加入的技术,它并不是什么划时代的新东西。早在 IE 6 时代,就有一个叫 userData 的东西用于本地存储,而当时考虑到浏览器兼容性,更通用的方案是使用 Flash。而如今,localStorage 被大多数浏览器所支持,如果你的网站需要支持 IE6+,那以 userData 作为你的 polyfill 的方案是种不错的选择。
sessionStorage
sessionStorage 与 localStorage 的接口类似,但保存数据的生命周期与 localStorage 不同。做过后端开发的同学应该知道 Session 这个词的意思,直译过来是“会话”。而 sessionStorage 是一个前端的概念,它只是可以将一部分数据在当前会话中保存下来,刷新页面数据依旧存在。但当页面关闭后,sessionStorage 中的数据就会被清空。
三者的异同
应用场景
有了对上面这些差别的直观理解,我们就可以讨论三者的应用场景了。
因为考虑到每个 HTTP 请求都会带着 Cookie 的信息,所以 Cookie 当然是能精简就精简啦,比较常用的一个应用场景就是判断用户是否登录。针对登录过的用户,服务器端会在他登录时往 Cookie 中插入一段加密过的唯一辨识单一用户的辨识码,下次只要读取这个值就可以判断当前用户是否登录啦。曾经还使用 Cookie 来保存用户在电商网站的购物车信息,如今有了 localStorage,似乎在这个方面也可以给 Cookie 放个假了~
而另一方面 localStorage 接替了 Cookie 管理购物车的工作,同时也能胜任其他一些工作。比如HTML5游戏通常会产生一些本地数据,localStorage 也是非常适用的。如果遇到一些内容特别多的表单,为了优化用户体验,我们可能要把表单页面拆分成多个子页面,然后按步骤引导用户填写。这时候 sessionStorage 的作用就发挥出来了。
安全性的考虑
需要注意的是,不是什么数据都适合放在 Cookie、localStorage 和 sessionStorage 中的。使用它们的时候,需要时刻注意是否有代码存在 XSS 注入的风险。因为只要打开控制台,你就随意修改它们的值,也就是说如果你的网站中有 XSS 的风险,它们就能对你的 localStorage 肆意妄为。所以千万不要用它们存储你系统中的敏感数据。
参考资料
- what is the difference between localStorage, sessionStorage, session and cookie?
- HTML5 localStorage security
- 维基百科 - Cookie
- Web Storage API
- 浏览器本地数据(sessionStorage、localStorage、cookie)与server端数据
- HTMl5的sessionStorage和localStorage
- HTML5 LocalStorage 本地存储
本文的版权归作者 邹润阳 所有,采用 Attribution-NonCommercial 3.0 License。任何人可以进行转载、分享,但不可在未经允许的情况下用于商业用途;转载请注明出处。感谢配合!
Using the Web Storage API
The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. This article provides a walkthrough of how to make use of this simple technology.
Basic concepts
Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do). You can access these values like an object, or with the Storage.getItem()
and Storage.setItem()
methods. These three lines all set the colorSetting entry in the same way:
localStorage.colorSetting = '#a4509b';localStorage['colorSetting'] = '#a4509b';localStorage.setItem('colorSetting', '#a4509b');
The two mechanisms within Web Storage are as follows:
sessionStorage
maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).localStorage
does the same thing, but persists even when the browser is closed and reopened.
These mechanisms are available via the Window.sessionStorage
and Window.localStorage
properties (to be more precise, in supporting browsers the Window
object implements the WindowLocalStorage
and WindowSessionStorage
objects, which the localStorage
and sessionStorage
properties hang off) — invoking one of these will create an instance of the Storage
object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage
and localStorage
for each origin — they function and are controlled separately.
So, for example, initially calling localStorage
on a document will return a Storage
object; calling sessionStorage
on a document will return a different Storage
object. Both of these can be manipulated in the same way, but separately.
Feature-detecting localStorage
To be able to use localStorage, we should first verify that it is supported and available in the current browsing session.
Testing for availability
Browsers that support localStorage will have a property on the window object named localStorage. However, for various reasons, just asserting that property exists may throw exceptions. If it does exist, that is still no guarantee that localStorage is actually available, as various browsers offer settings that disable localStorage. So a browser may supportlocalStorage, but not make it available to the scripts on the page. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account.
Here is a function that detects whether localStorage is both supported and available:
function storageAvailable(type) { try { var storage = window[type], x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); return true; } catch(e) { return e instanceof DOMException && ( // everything except Firefox e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === 'QuotaExceededError' || // Firefox e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && // acknowledge QuotaExceededError only if there's something already stored storage.length !== 0; }}
And here is how you would use it:
if (storageAvailable('localStorage')) { // Yippee! We can use localStorage awesomeness}else { // Too bad, no localStorage for us}
You can test for sessionStorage instead by calling storageAvailable('sessionStorage')
.
See here for a brief history of feature-detecting localStorage.
A simple example
To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the color, font, and decorative image:
When you choose different options, the page is instantly updated; in addition, your choices are stored in localStorage
, so that when you leave the page and load it again later on, your choices are remembered.
We have also provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a StorageEvent
is fired.
Testing whether your storage has been populated
To start with on main.js, we will test whether the storage object has already been populated (i.e., the page was previously accessed):
if(!localStorage.getItem('bgcolor')) { populateStorage();} else { setStyles();}
The Storage.getItem()
method is used to get a data item from storage; in this case we are testing to see whether the bgcolor
item exists; if not, we run populateStorage()
to add the existing customization values to the storage. If there are already values there, we run setStyles()
to update the page styling with the stored values.
Note: You could also use Storage.length
to test whether the storage object is empty or not.
Getting values from storage
As noted above, values can be retrieved from storage using Storage.getItem()
. This takes the key of the data item as an argument, and returns the data value. For example:
function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.getElementById('bgcolor').value = currentColor; document.getElementById('font').value = currentFont; document.getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage);}
Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload.
Setting values in storage
Storage.setItem()
is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it.
function populateStorage() { localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); localStorage.setItem('font', document.getElementById('font').value); localStorage.setItem('image', document.getElementById('image').value); setStyles();}
The populateStorage()
function sets three items in local storage — the background color, font, and image path. It then runs the setStyles()
function to update the page styles, etc.
We've also included an onchange
handler on each form element, so that the data and styling is updated whenever a form value is changed:
bgcolorForm.onchange = populateStorage;fontForm.onchange = populateStorage;imageForm.onchange = populateStorage;
Responding to storage changes with the StorageEvent
The StorageEvent
is fired whenever a change is made to the Storage
object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.
On the events page (see events.js) the only JavaScript is as follows:
window.addEventListener('storage', function(e) { document.querySelector('.my-key').textContent = e.key; document.querySelector('.my-old').textContent = e.oldValue; document.querySelector('.my-new').textContent = e.newValue; document.querySelector('.my-url').textContent = e.url; document.querySelector('.my-storage').textContent = e.storageArea;});
Here we add an event listener to the window
object that fires when the Storage
object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself.
Deleting data records
Web Storage also provides a couple of simple methods to remove data. We don't use these in our demo, but they are very simple to add to your project:
Storage.removeItem()
takes a single argument — the key of the data item you want to remove — and removes it from the storage object for that domain.Storage.clear()
takes no arguments, and simply empties the entire storage object for that domain.
Specifications
Browser compatibility
- Desktop
- Mobile
All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.
See also
- Web Storage API landing page
- the storage of information of web app
- THE PAST, PRESENT & FUTURE OF LOCAL STORAGE FOR WEB APPLICATIONS
- The visual Display of information
- Information Systems : The State of the Field
- Information Systems : The State of the Field
- Get The Information of The Screen
- The App of WebDesign
- 论文原稿:Research on the Status Quo and System architecture of the Web Information Resource Evaluation
- Online Information Storage: Completing the Web as Platform
- The Handbook of Information Systems Research
- The New School of Information Security
- The Handbook of Information and Computer Ethics
- Get some information of the file
- The help information of Squirrel.Nutz
- The holy grail of network storage management
- The VMware View of Softeare Defined Storage
- web app & part of the design for a german corp
- The content of element type "web-app" must match "
- HDU 2084 数塔
- ELK日志分析平台的搭建以及beats模式的搭建
- 爬虫入门-03-12306官网登录详解
- 多研究些架构,少谈些主义(4)-- 架构师是技术的使用者而不是信徒
- DrawerLayout侧滑菜单点击切换Xlistview
- the storage of information of web app
- recycleview条目点击事件
- 360新版特性界面实现(1)
- Deep learning学习步骤
- js实现文字无缝轮播
- select 二级联动
- 从DLL中导出函数
- 记一次处理V4包冲突...
- 重读 JVM