在h5中,新增了localStorage,對應localStorage的有一個storage事件,這個事件可以用來進行頁面間進行通信。
頁面間通信的列子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A</title>
</head>
<body>
<button>click2</button>
</body>
<script>
document.querySelector('button').onclick = function(){
localStorage.setItem('Num', Math.random()*10);
}
window.addEventListener("storage", function (e) {
console.log(e)
console.log(e.newValue)
alert('來自其他頁面的localstorage');
});
var orignalSetItem = localStorage.setItem;
localStorage.setItem = function(key,newValue){
var setItemEvent = new Event("setItemEvent");
setItemEvent.newValue = newValue;
window.dispatchEvent(setItemEvent);
alert('來自本頁面的localstorage');
orignalSetItem.apply(this,arguments);
}
window.addEventListener("setItemEvent", function (e) {
alert(e.newValue);
});
</script>
</html>
可以用兩個一模一樣的頁面進行上面測試代碼的驗證,其中頁面間通信主要使用的是
window.addEventListener("storage", function (e) {});
有以下幾點需要注意:
- 該事件只能監聽的其他頁面的setItem觸發的storage事件
- 必須是同源的頁面(即協議、端口、域名都相同)
而在當前頁面,我使用了對localStorage.setItem
方法的改造,在改造的函數中,我們使用了自定義事件,並對該事件進行了監聽。
在實際的使用中,遇到如下問題:
IE9-11中不接受改造的setItem方法,改造setItem方法後,會導致localStorage調用setItem方法報錯
基於這種兼容性的問題,建議不要更改setItem方法
詳細的列子,可訪問如下頁面:
https://alizwell.github.io/front-end/JS/PageMessageA.html
https://alizwell.github.io/front-end/JS/PageMessageB.html