超越cookie - 使用DOM sessionStorage和localStorage来保存更多信息

JavaScript cookie可能不会成为存档和持久化信息的可靠方式,但它的小尺寸限制(对于大多数浏览器,每个域4kb)越来越成为一个问题。当然,您只需在服务器上存储大量信息,但这会给服务器带来额外的请求,更重要的是,如果您希望Web应用程序在用户离线时仍能正常运行,则会失败。为了更好地满足当今网络应用的需求, 5个被淘汰出了两个新的方法来存储在客户端边信息和 (统称为DOM存储)。DOM Storage的主要特点是:sessionStoragelocalStorage

  • 可以存储比JavaScript cookie更多的信息。确切的数量因浏览器而异,但在FF3 +,Chrome4 +和Safari4 +中,每个存储区域为5MB,而在IE8 +中则为10 MB

  • 以下浏览器支持DOM存储(sessionStorage和 localStorage) - FF3.5 +,Chrome4 +,Safari4 +,Opera10.5 +和IE8 +

  • 对于sessionStorage这是我们用来存储依旧只能通过浏览器会话的寿命数据对象,其不同之处在于数据不JavaScript的饼干 跨浏览器标签仍然存在。然而,在某些浏览器中,数据确实在浏览器崩溃时存在,例如FF。

  • 具体而言,使用DOM存储存储的数据 localStorage不会自动过期。

DOM存储对象(sessionStorage和 localStorage)都继承了同一组属性和方法。他们是:

DOM存储对象
方法描述
的getItem(钥匙)返回基于DOM存储区域内指定键的值。如果不存在相应的密钥,null则返回。
setItem(键,值)使用DOM存储区域内的指定键存储字符串值。如果此类密钥已存在,则存储在该位置的先前值将替换为新值。
的removeItem(钥匙)根据DOM存储区域内的指定键删除值。
键(索引)返回指定索引处内容项的键,其中index是基于零的整数,对应于DOM存储区域中项的位置。请注意,添加或删除项目时,每个项目的位置可能会更改。
明确()清除当前域的DOM存储区域中的所有数据。
性能 
长度只读属性,返回DOM存储区域中的项目数。

 window.sessionStorage对象

sessionStorage对象用于存储应该仅持续浏览器会话持续时间的数据。重新加载或返回到同一浏览器会话中的页面时,将保留该信息:

1

2

3

4

6

7

8

9

10

if (window.sessionStorage){

    sessionStorage.setItem("mykey", "Some Value") //store data using setItem()

    var persistedval=sessionStorage.getItem("mykey") //returns "Some Value"

 

    sessionStorage.mykey2="Some Value 2" //store data using the dot notation

    var persistedval2=sessionStorage.mykey2 //returns "Some Value 2"

 

    sessionStorage["mykey3"]="Some Value 3" //store data using the square bracket notation

    var persistedval3=sessionStorage["mykey3"] //returns "Some Value 3"

}

如上所示,可以使用getItem()和设置和检索值setItem(),或者通过直接引用键作为对象的属性来设置和检索值 。

虽然sessionStorage行为类似于JavaScript会话cookie,但它在以下关键方面有所不同:

  • 分配给每个sessionStorage区域的存储限制为5MB(IE8中为10 MB),而对于cookie,则为4KB(IE8中为10KB)。

  • 使用的数据sessionStorage不会在浏览器选项卡中保留,即使两个选项卡都包含来自同一域源的网页也是如此。换句话说,内部数据sessionStorage不仅限于调用页面的域和目录,而且还包含页面所在的浏览器选项卡。与会话cookie形成对比,会话cookie将数据从选项卡保留到选项卡。

  • 在某些浏览器(如FF3.5 +)中,使用的数据 sessionStorage将在浏览器崩溃后继续存在。这意味着如果浏览器因崩溃而关闭,sessionStorage 则重新启动浏览器时仍会保留最近存储的内部信息。

以下示例会自动将TEXTAREA的内容保存到sessionStorage用户输入的内容中,以便在浏览器刷新或崩溃时(目前仅限FF3.5 +)挽救内容。以下TEXTAREA的内容将在页面的硬刷新后继续存在,并且在支持浏览器的情况下,浏览器也会崩溃:

1

2

3

4

6

7

8

9

10

11

12

13

14

15

16

<form>

<textarea id="feedback" style="width:350px;height:200px"></textarea><br />

<input type="button" value="Click to Hard Reload Page" onClick="location.reload(true)" />

</form>

 

<script type="text/javascript">

if (window.sessionStorage){

    var feedbackarea=document.getElementById("feedback")

    if (sessionStorage.feedbackdata){ //if there is data stored for the target textarea

        feedbackarea.value=sessionStorage.feedbackdata //recall it upon refresh or crash

    }

    feedbackarea.onkeyup=function(e){

        sessionStorage.feedbackdata=this.value //save contents of textarea as user types

    }

}

</script>

演示(FF3.5 +,Chrome4 +,Safari4 +,Opera10.5 +或IE8 +):

 

 

 window.localStorage对象(以及FF3.0的window.globalStorage [location.hostname])

localStorage对象可以被认为是持久化版本sessionStorage。而后者仅适用于浏览器选项卡会话期间持续,localStorage仍然存在任何无限期保存用户的数据帕特和跨浏览器选项卡(类似于JavaScript的饼干)。存储大小与存储大小相同。localStoragesessionStorage

在FF中,localStorage仅从FF3.5开始添加对对象的支持。在FF3.0浏览器中,存在不规范globalStorage[location.hostname]等价的对象,你可以使用最大化浏览器COM兼容性。考虑到这一点,下面显示了一个简单的计数器,显示用户在其历史记录中访问当前页面的次数:

1

2

3

4

6

7

8

9

10

11

<script type="text/javascript">

var mydomstorage=window.localStorage || (window.globalStorage? globalStorage[location.hostname] : null)

if (mydomstorage){

    var i=(mydomstorage.pagecount)? parseInt(mydomstorage.pagecount)+1 : 1

    document.write("You have visited this page <b>" + i + " </b> times altogether.")

    mydomstorage.pagecount=i

}

else{

    document.write("<b>Your browser doesn't support DOM Storage unfortunately.</b>")

}

</script>

演示(需要FF3 +,Chrome4 +,Safari4 +,Opera10.5 +或IE8 +): 您已经访问过此页面1次。

 使用DOM存储创建可编辑的待办事项列表

现在是时候稍微雄心勃勃了。让我们利用DOM Storage提供的宽敞空间创建一个可编辑的记事本,用户可以在其中输入待办事项列表,这些项目会自动保留在用户的硬盘上,因此始终会保存所有更改。我们使用HTML 5的contenteditable属性来使DIV的内容可编辑:

1

2

3

4

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

三十

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

<style type="text/css">

 

#todolist{

    width:200px;

    height: 200px;

    font:normal 13px Arial;

    background:lightyellow;

    border:1px dashed gray;

    overflow-y:scroll;

    padding:5px;

}

 

#todolist ol{

    margin-left:-15px;

}

 

#todolist li{

    border-bottom:1px solid gray;

    margin-bottom:8px;

}

 

 

</style>

 

<body>

 

<div id="todolist" contenteditable="true">

<div contenteditable="false"><b>Edit To-Do List (auto saved):</b></div>

    <ol>

    <li>Take out garbage</li>

    <li>Finish report</li>

    <li>Set alarm to 6am</li>

    </ol>

</div>

<a href="#" onClick="resetlist();return false">Reset To Do List</a>

 

<script type="text/javascript">

 

var default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>='<div contenteditable="false"><b>Edit To-Do List (auto saved):</b></div>\n' //remember default contents of to-do list

default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>+='<ol>\n'

default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>+='<li>Take out garbage</li>\n'

default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>+='<li>Finish report</li>\n'

default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>+='<li>Set alarm to 6am</li>\n'

default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>+='</ol>'

 

function resetlist(){

    todolistref.inner<span class="THmo acWHSet" txhidy15="acWHSet" data="html">HTML</span>=default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>

    domstorage.todolistdata=default<span class="THmo acWHSet" txhidy15="acWHSet" data="html">html</span>

}

 

var todolistref=document.getElementById("todolist")

 

var domstorage=window.localStorage || (window.globalStorage? globalStorage[location.hostname] : null)

if (domstorage){

    if (domstorage.todolistdata){ //if there is data stored for the to-do list

        todolistref.inner<span class="THmo acWHSet" txhidy15="acWHSet" data="html">HTML</span>=domstorage.todolistdata //recall it

    }

    todolistref.onkeyup=function(e){

        domstorage.todolistdata=this.inner<span class="THmo acWHSet" txhidy15="acWHSet" data="html">HTML</span>

    }

}

 

</script>

演示(FF3.5 +,Chrome4 +,Safari4 +,Opera10.5 +或IE8 +):

 

尝试编辑或添加到列表中(在最后一个条目后按Enter键)。每次按下击键时,内容都会自动保存到DOM存储器中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值