传统的cookie可以在浏览器中通过文本格式保存简单的数据,如登录的用户名等;而在HTML5标准中又增加了localStorage、sessionStorage等客户端数据存储方案,本文将讨论相关应用。
cookie数据使用doucment对象的cookie属性存储和读取,其类型为字符串,可以使用max-age参数设置数据的有效期,单位为秒;参数和数据使用分号(;)分隔,下面的代码演示了cookie数据的写入和读取。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <button type="button" onclick="showCookie();">显示Cookie数据</button> </body> </html> <script> window.onload = function () { document.cookie = "Tom;max-age=10"; }; // function showCookie() { let s = document.cookie; alert(s); } </script>
代码中,在页面加载后会保存cookie数据"Tom",设置有效时间为10秒,点击页面的"显示Cookie数据"按钮可以显示数据内容(不会显示max-age参数数据);打开页面后,10秒内点击按钮可以显示Tom,10秒之后cookie数据会清除,点击按钮显示为空白。
cookie数据是以明文形式保存,所以,不应将敏感信息保存在cookie中;此外,cookie数据只在当前页面中有效。
HTML5标准中新增了localStorage和sessionStorage对象,用于在浏览器中保存数据,它们的区别在于,localStorage对象保存的数据可以在当前页面写入和读取,只要不清除浏览器缓存,下次打开页面时还会存在;sessionStorage对象用于保存临时,数据只在当前页面、当前会话有效,关闭当前会话窗口或标签后数据就会被清除。
除应用范围不同以外,localStorage和sessionStorage对象的操作方法相似,常用的方法包括:
下面的代码演示了localStorage对象的应用。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <button type="button" onclick="saveData();">保存数据</button> <button type="button" onclick="showData();">显示数据</button> </body> </html> <script> // function saveData() { localStorage.setItem("username", "Tom"); } // function showData() { alert(localStorage.getItem("username")); } </script>
页面会显示两个按钮,其中,点击“保存数据”按钮会将名为"username"的数据保存到localStorage对象,其值为"Tom";点击“显示数据”按钮会显示"Tom"。关闭页面并再次打开,直接点击“显示数据”按钮可以看到数据依然存在。
下面的代码演示sessionStorage对象的应用。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <button type="button" onclick="saveData();">保存数据</button> <button type="button" onclick="showData();">显示数据</button> </body> </html> <script> // function saveData() { sessionStorage.setItem("username", "Tom"); } // function showData() { alert(sessionStorage.getItem("username")); } </script>
页面中,点击“保存数据”按钮会将名为"username"的数据保存到sessionStorage对象,其值为"Tom";点击“显示数据”按钮会显示"Tom"。关闭页面并再次打开,直接点击“显示数据”按钮则会显示null,即上次保存的数据已删除。