今天写了一个demo,发现无法触发window.addEventListener('storage',()=>{});
查了一下资料,发现这是其他标签页面触发。
另外,storage事件只能监听到localStorage的变化
只能怪自己看书籍不够细心。
<!DOCTYPE html>
<html>
<head>
<title>利用storage事件实时监视Web Storage中的数据</title>
<script>
window.addEventListener('storage', function (event) {
if (event.key == "test") {
var output = document.getElementById("output");
output.innerHTML = "原有值:" + event.oldValue;
output.innerHTML += "<br/>新值:" + event.newValue;
output.innerHTML += "<br/>变动页面地址:" +
utf8_decode(unescape(event.url));
console.log(event.storageArea);
// 此行代码只在Chrome浏览器中有效
console.log(event.storageArea === localStorage); // 输出true
}
}, false);
function utf8_decode(utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6)
| (c3 & 63));
i += 3;
}
}
return string;
}
</script>
</head>
<script>
function setLocalStorage() {
localStorage.test = document.getElementById("text1").value;
}
</script>
<body>
请输入一些值:<input type="text" id="text1" />
<button onClick="setLocalStorage()">设置</button>
<output id="output"></div>
</body>
</html>