<video src="https://mp-162001ea-cc91-4f6f-80ea-c4ee663788c2.cdn.bspapp.com/newBlog/8cde03d9d1c5cc36d4f1fab26d18bac6.mp4" controls=""></video>
一个窗口更新localStorage,另一个窗口监听window对象的”storage”事件,来实现通信。 注:两个页面要同源(URL的协议、域名和端口相同)
// 本窗口的设值代码
localStorage.setItem('aaa', (Math.random()*10).toString())
// 其他窗口监听storage事件
window.addEventListener("storage", function (e) {
console.log(e)
console.log(e.newValue)
})
所有的WebSocket都监听同一个服务器地址,利用send发送消息,利用onmessage获取消息的变化,不仅能窗口,还能跨浏览器,兼容性最佳,只是需要消耗点服务器资源。
var ws = new WebSocket("ws://localhost:3000/")
ws.onopen = function (event) {
// 或者把此方法注册到其他事件中,即可与其他服务器通信
ws.send({now : Date.now()}); // 通过服务器中转消息
};
ws.onmessage = function (event) {
// 消费消息
console.log(event.data);
}
借助iframe 或 window.open 回顾一下API
otherWindow.postMessage(message, targetOrigin, [transfer]);
/*
* A窗口的域名是<http://example.com:8080>,以下是A窗口的script标签下的代码:
*/
var popup = window.open(...popup details...);
// 如果弹出框没有被阻止且加载完成
// 这行语句没有发送信息出去,即使假设当前页面没有改变location(因为targetOrigin设置不对)
popup.postMessage("The user is 'bob' and the password is 'secret'",
"https://secure.example.net");
// 假设当前页面没有改变location,这条语句会成功添加message到发送队列中去(targetOrigin设置对了)
popup.postMessage("hello there!", "http://example.org");
function receiveMessage(event)
{
// 我们能相信信息的发送者吗? (也许这个发送者和我们最初打开的不是同一个页面).
if (event.origin !== "http://example.org")
return;
// event.source 是我们通过window.open打开的弹出页面 popup
// event.data 是 popup发送给当前页面的消息 "hi there yourself! the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);
/*
* 弹出页 popup 域名是<http://example.org>,以下是script标签中的代码:
*/
//当A页面postMessage被调用后,这个function被addEventListenner调用
function receiveMessage(event)
{
// 我们能信任信息来源吗?
if (event.origin !== "http://example.com:8080")
return;
// event.source 就当前弹出页的来源页面
// event.data 是 "hello there!"
// 假设你已经验证了所受到信息的origin (任何时候你都应该这样做), 一个很方便的方式就是把enent.source
// 作为回信的对象,并且把event.origin作为targetOrigin
event.source.postMessage("hi there yourself! the secret response " +
"is: rheeeeet!",
event.origin);
}
window.addEventListener("message", receiveMessage, false);
在页面A设置一个使用 setInterval 定时器不断刷新,检查 Cookies 的值是否发生变化,如果变化就进行刷新的操作。
由于 Cookies 是在同域可读的,所以在页面 B 审核的时候改变 Cookies 的值,页面 A 自然是可以拿到的。
这样做确实可以实现我想要的功能,但是这样的方法相当浪费资源。虽然在这个性能过盛的时代,浪费不浪费也感觉不出来,但是这种实现方案,确实不够优雅。
HTML5 中的 Web Worker 可以分为两种不同线程类型,一个是专用线程 Dedicated Worker,一个是共享线程 Shared Worker。
其实就是直接获取对方DOM,适用于两个页面在同一域;可以传递对象数据(对象数据使用 instanceof 做类型判断时有坑);参考 window.open; 例:
// 父页面获取子iframe
document.getElementById('iframe的id').contentWindow.document
// 子iframe获取父页面
window.parent.document
浏览器窗口有window.name属性。这个属性的最大特点是,无论是否同源,只要在同一个窗口里,前一个网页设置了这个属性,后一个网页可以读取它。
父窗口先打开一个子窗口,载入一个不同源的网页,该网页将信息写入window.name属性。
window.name = data;
接着,子窗口跳回一个与主窗口同域的网址。
window.location.href = 'http://parent.url.com/xxx.html';
然后,主窗口就可以读取子窗口的window.name了。
var data = document.getElementById('iframe的id').contentWindow.name;
这种方法的优点是,window.name容量很大,可以放置非常长的字符串;缺点是必须监听子窗口window.name属性的变化,影响网页性能。