1、localStorage一個窗口更新localStorage,另一個窗口監(jiān)聽window對象的”storage”事件,來實現(xiàn)通信。 // 本窗口的設(shè)值代碼
localStorage.setItem('aaa', (Math.random()*10).toString())
// 其他窗口監(jiān)聽storage事件
window.addEventListener("storage", function (e) {
console.log(e)
console.log(e.newValue)
})2、WebSocket所有的WebSocket都監(jiān)聽同一個服務(wù)器地址,利用send發(fā)送消息,利用onmessage獲取消息的變化,不僅能窗口,還能跨瀏覽器,兼容性最佳,只是需要消耗點服務(wù)器資源。 var ws = new WebSocket("ws://localhost:3000/")
ws.onopen = function (event) {
// 或者把此方法注冊到其他事件中,即可與其他服務(wù)器通信
ws.send({now : Date.now()}); // 通過服務(wù)器中轉(zhuǎn)消息
};
ws.onmessage = function (event) {
// 消費消息
console.log(event.data);
}3、postMessage借助iframe 或 window.open,回顧一下API
/*
* A窗口的域名是<http://:8080>,以下是A窗口的script標(biāo)簽下的代碼:
*/
var popup = window.open(...popup details...);
// 如果彈出框沒有被阻止且加載完成
// 這行語句沒有發(fā)送信息出去,即使假設(shè)當(dāng)前頁面沒有改變location(因為targetOrigin設(shè)置不對)
popup.postMessage("The user is 'bob' and the password is 'secret'",
"https://secure.");
// 假設(shè)當(dāng)前頁面沒有改變location,這條語句會成功添加message到發(fā)送隊列中去(targetOrigin設(shè)置對了)
popup.postMessage("hello there!", "http://");
function receiveMessage(event)
{
// 我們能相信信息的發(fā)送者嗎? (也許這個發(fā)送者和我們最初打開的不是同一個頁面).
if (event.origin !== "http://")
return;
// event.source 是我們通過window.open打開的彈出頁面 popup
// event.data 是 popup發(fā)送給當(dāng)前頁面的消息 "hi there yourself! the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);
/*
* 彈出頁 popup 域名是<http://>,以下是script標(biāo)簽中的代碼:
*/
//當(dāng)A頁面postMessage被調(diào)用后,這個function被addEventListenner調(diào)用
function receiveMessage(event)
{
// 我們能信任信息來源嗎?
if (event.origin !== "http://:8080")
return;
// event.source 就當(dāng)前彈出頁的來源頁面
// event.data 是 "hello there!"
// 假設(shè)你已經(jīng)驗證了所受到信息的origin (任何時候你都應(yīng)該這樣做), 一個很方便的方式就是把enent.source
// 作為回信的對象,并且把event.origin作為targetOrigin
event.source.postMessage("hi there yourself! the secret response " +
"is: rheeeeet!",
event.origin);
}
window.addEventListener("message", receiveMessage, false);新片場https://www./sites/73286.html 傲視網(wǎng)https://www./sites/73285.html 4、cookie + setInterval【差】在頁面A設(shè)置一個使用 setInterval 定時器不斷刷新,檢查 Cookies 的值是否發(fā)生變化,如果變化就進行刷新的操作。 由于 Cookies 是在同域可讀的,所以在頁面 B 審核的時候改變 Cookies 的值,頁面 A 自然是可以拿到的。 這樣做確實可以實現(xiàn)我想要的功能,但是這樣的方法相當(dāng)浪費資源。雖然在這個性能過盛的時代,浪費不浪費也感覺不出來,但是這種實現(xiàn)方案,確實不夠優(yōu)雅。 5、SharedWorkerhtml5 中的 Web Worker 可以分為兩種不同線程類型,一個是專用線程 Dedicated Worker,一個是共享線程 Shared Worker。
6、直接引用適用于兩個頁面在同一域;可以傳遞對象數(shù)據(jù)(對象數(shù)據(jù)使用 instanceof 做類型判斷時有坑);參考 window.open; |
|
|