我们来看运行结果:

浏览器不能删除我们通过localStorage创建的数据,除非用户删除它。
2.监听Storage事件
通过local storage存储的数据对同源的文档具有可见性,比如你打开两个chrome浏览器访问同一个url地址,在任何一个页面上创建的local storage对另外一个页面也是可见的。但是如果用别的浏览器(如firefox)打开相同url地址,local storage是不可见的,因为他们不同源了。Storage事件就是用来监听storage的内容发生改变的,下面我们看他包含哪些属性:
key:返回发生改变的key值;
oldValue:返回发生改变key值以前的value值;
newValue:返回发生改变key值新的value值;
url:发生改变的url地址;
storageArea:返回发生改变的Storage对象(是local storage还是session storage)。
下面我们看个例子:
<!DOCTYPE HTML>
<html>
<head>
<title>Storage</title>
<style>
table{border-collapse: collapse;}
th, td{padding: 4px;}
</style>
</head>
<body>
<table id="data" border="1">
<tr>
<th>key</th>
<th>oldValue</th>
<th>newValue</th>
<th>url</th>
<th>storageArea</th>
</tr>
</table>
<script>
var tableElement = document.getElementById('data');
window.onstorage = function (e) {
var row = '<tr>';
row += '<td>' + e.key + '</td>';
row += '<td>' + e.oleValue + '</td>';
row += '<td>' + e.newValue + '</td>';
row += '<td>' + e.url + '</td>';
row += '<td>' + (e.storageArea == localStorage) + '</td></tr>';
tableElement.innerHTML += row;
}
</script>
</body>
</html>
我们在例1中增删改storage的数据,会在例2页面上显示出来。例2在chrome浏览器中运行正常,firefox没有反应,其他浏览器没有测试。
运行结果:

3.使用session storage
session storage在使用上和local storage一样,只是他的访问性上只限于当前页面,并且页面关闭后会消失,我们通过sessionStorage来访问它。
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
body > *{float: left;}
table{border-collapse: collapse;margin-left: 50px;}
th, td{padding: 4px;}
th{text-align: right;}
input{border: thin solid black;padding: 2px;}
label{min-width: 50px;display: inline-block;text-align: right;}
#countmsg, #buttons{margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}
</style>
</head>
<body>
<div>
<div>
<label>Key:</label><input id="key" placeholder="Enter Key" /></div>
<div>
<label>Value:</label><input id="value" placeholder="Enter Value" /></div>
<div id="buttons">
<button id="add">Add</button>
<button id="clear">Clear</button>
</div>
<p id="countmsg">There are <span id="count"></span>items</p>
</div>
<table id="data" border="1">
<tr>
<th>Item Count:</th>
<td id="count">-</td>
</tr>
</table>
<iframe src="storage.html" width="500" height="175"></iframe>
<script>
displayData();
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e) {
switch (e.target.id) {
case 'add':
var key = document.getElementById("key").value;
var value = document.getElementById("value").value;
sessionStorage.setItem(key, value);
break;
case 'clear':
sessionStorage.clear();
break;
}
displayData();
}
function displayData() {
var tableElement = document.getElementById('data');
tableElement.innerHTML = '';
var itemCount = sessionStorage.length;
document.getElementById('count').innerHTML = itemCount;
for (var i = 0; i < itemCount; i++) {
var key = sessionStorage.key(i);
var val = sessionStorage.getItem(key);
tableElement.innerHTML += "<tr><th>" + key + ":</th><td>" + val + "</td></tr>";
}
}
</script>
</body>
</html>