Files
knowledge-kit/Chapter2 - Web FrontEnd/2.27.md
2020-02-25 17:46:51 +08:00

49 lines
1.5 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 浏览器不通窗口之间的通信
## localStorage
“同源”情况下,一个窗口更新 localStorage另一个窗口监听 window 对象的 “storage” 事件,来实现通信
```
window.localStorage.setItem('name','杭城小刘');
window.addEventListener('storage', function (e) {
console.log(e);
console.log(e.newValue);
})
```
## WebSocket
所有的 WebSocket 都监听同一个服务器地址,利用 `send` 发消息,利用 `onmessage` 获取消息的变化,不仅能窗口,还可以跨浏览器通信,兼容性最佳。只是需要消耗点服务器资源
```
var ws = new WebSockte('ws://192.168.0.0.1:8080/');
ws.onopen = function (event) {
ws.send({now: new Date()});
}
ws.onmessage = function (event) {
console.log(event)
}
```
## postMessage
借助 iframe 或 window.open
```
otherWindow.postMessage(message targetOrigin, [transfer])
```
## cookie + setInterval
在页面 A 设置一个使用 setInterval 定时器不断刷新,检查 Cookies 的值是否变化,如果变化就是进行刷新操作
由于 Cookies 在同一个域下可读,所以这样做的缺点是浪费资源
## SharedWorker
HTML5 中的 Web Worker 可以分为2种不同线程类型一种是专用线程 Dedicated Worker一种是共享线程 Shared Worker
- Dedicated Worker 直接使用 new Worker() 创建,这种 webWorker 是当前页面专有的
- SharedWorker 可以被多个 window、标签页、iframe 共同使用,但必须保证这些标签页都是同源的