事件屬性
在事件處理函數中,觸發事件的事件對象(event參數值)具有如下幾個屬性
event.key 屬性:屬性值爲在 session 或 localStorage 中被修改的數據鍵值。
event.oldValue 屬性:屬性值爲在 sessionStorage 或 localStorage 中被修改的值。
event.newValue 屬性:屬性值爲在 sessionStorage 或 localStorage 中被修改後的值
event.url 屬性:屬性值爲修改 sessionStorage 或 localStorage 中值的頁面的URL地址
event.storageArea 屬性 : 屬性值爲被變動的 sessionStorage 對象或 localStorage 對象
使用函數
charCodeAt() 可返回指定位置的字符的 Unicode 編碼。這個返回值是 0 - 65535 之間的整數。
fromCharCode() 可接受一個指定的 Unicode 值,然後返回一個字符串。
unescape() 可對通過 escape() 編碼的字符串進行解碼。
Unicode碼部分註解
Unicode只有一個字符集,中、日、韓的三種文字佔用了Unicode中0x3000到0x9FFF的部分 Unicode目前普遍採用的是UCS-2,它用兩個字節來編碼一個字符, 比如漢字”經”的編碼是0x7ECF,注意字符碼一般用十六進制來 表示,爲了與十進制區分,十六進制以0x開頭,0x7ECF轉換成十進制 就是32463,UCS-2用兩個字節來編碼字符,兩個字節就是16位二進制, 2的16次方等於65536,所以UCS-2最多能編碼65536個字符。 編碼從0到127的字符與ASCII編碼的字符一樣,比如字母”a”的Unicode 編碼是0x0061,十進制是97,而”a”的ASCII編碼是0x61,十進制也是97, 對於漢字的編碼,事實上Unicode對漢字支持不怎麼好,這也是沒辦法的, 簡體和繁體總共有六七萬個漢字,而UCS-2最多能表示65536個,才六萬 多個,所以Unicode只能排除一些幾乎不用的漢字,好在常用的簡體漢字 也不過七千多個,爲了能表示所有漢字,Unicode也有UCS-4規範,就是用 4個字節來編碼字符
Unicode碼圖冊
實際效果
實時監聽的頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>利用storage事件實時監視Web Storage中的數據</title>
</head>
<body>
<script type="text/javascript">
//利用storage事件實時監視wev Storage中的數據
window.addEventListener('storage',function (e) {//e只是一個傳參
//獲取被修改的鍵值
if (e.key == 'test') {
//獲取將要被添加內容的元素
var output = document.getElementById('output');
//將獲取到的修改值在元素中輸出
output.innerHTML = '原有值:' + e.oldValue;
output.innerHTML += '<br />新值:' + e.newValue;
output.innerHTML += '<br />變動頁面地址:' + utf8_decode(unescape(e.url));
//分別打印會發現內容一致
console.log(e.storageArea);
console.log(localStorage);
//此行代碼只在Chrome瀏覽器中有效
console.log(e.storageArea === localStorage);//輸出true
}
},false);
function utf8_decode (utftext) {
var string = '';
var i = c = c1 = c2 = 0;
//獲取URL所有字符
while (i < utftext.length) {
//獲取URL並將URL中所有 Unicode 編碼獲取
c = utftext.charCodeAt(i);
//對 Unicode 編碼進行處理轉化成字符串
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>
<output id="output"></output>
</body>
</html>
被監聽的頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用於修改localStorage 中數據的頁面的代碼</title>
</head>
<body>
<script type="text/javascript">
function setLOcalStorage () {
//設置test鍵值下的內容等於input框中的內容
localStorage.test = document.getElementById('text1').value;
}
</script>
請輸入一些值:<input type="text" id="text1" />
<button onclick="setLOcalStorage()">設置</button>
</body>
</html>