├── docs
├── SharedWorker
│ ├── style.css
│ ├── worker.js
│ ├── index.html
│ ├── page1.html
│ ├── page2.html
│ └── page3.html
├── localStorage
│ ├── index.html
│ ├── page1.html
│ └── page2.html
├── setInterval
│ ├── index.html
│ ├── page1.html
│ └── page2.html
├── BroadcastChannel
│ ├── index.html
│ ├── page2.html
│ └── page1.html
└── index.html
└── README.md
/docs/SharedWorker/style.css:
--------------------------------------------------------------------------------
1 | html,
2 | body,
3 | section {
4 | height: 98%;
5 | margin: 0;
6 | }
7 |
8 | section {
9 | display: flex;
10 | }
11 |
12 | iframe {
13 | flex: 1;
14 | height: 100%;
15 | width: 30%;
16 | }
--------------------------------------------------------------------------------
/docs/SharedWorker/worker.js:
--------------------------------------------------------------------------------
1 | var portList = [];
2 |
3 | onconnect = function(e) {
4 | var port = e.ports[0];
5 | ensurePorts(port);
6 | port.onmessage = function(e) {
7 | var data = e.data;
8 | disptach(port, data);
9 | };
10 | port.start();
11 | };
12 |
13 | function ensurePorts(port) {
14 | if (portList.indexOf(port) < 0) {
15 | portList.push(port);
16 | }
17 | }
18 |
19 | function disptach(selfPort, data) {
20 | portList
21 | .filter(port => selfPort !== port)
22 | .forEach(port => port.postMessage(data));
23 | }
24 |
--------------------------------------------------------------------------------
/docs/localStorage/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | localStorage
8 |
24 |
25 |
26 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/docs/setInterval/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | setInterval
8 |
24 |
25 |
26 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/docs/BroadcastChannel/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | BroadcastChannel
8 |
24 |
25 |
26 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | 页面通讯
8 |
9 |
10 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/docs/SharedWorker/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | SharedWorker
8 |
26 |
27 |
28 |
33 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/docs/BroadcastChannel/page2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | BroadcastChannel Page 1
8 |
9 |
10 | Page 2
11 |
12 |
19 |
20 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/docs/BroadcastChannel/page1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | BroadcastChannel Page 1
8 |
9 |
10 | Page 1
11 |
18 |
19 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/docs/localStorage/page1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | localStorage Page 1
8 |
9 |
10 | Page 1
11 |
18 |
19 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/docs/localStorage/page2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | localStorage Page 1
8 |
9 |
10 | Page 2
11 |
18 |
19 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/docs/SharedWorker/page1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | BroadcastChannel Page 1
8 |
9 |
10 | Page 1
11 |
18 |
19 |
20 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/docs/SharedWorker/page2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | BroadcastChannel Page 1
8 |
9 |
10 | Page 2
11 |
18 |
19 |
20 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/docs/SharedWorker/page3.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | BroadcastChannel Page 1
8 |
9 |
10 | Page 3
11 |
18 |
19 |
20 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/docs/setInterval/page1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | setInterval Page 1
8 |
9 |
10 | Page 1
11 |
18 |
19 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/docs/setInterval/page2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | setInterval Page 1
8 |
9 |
10 | Page 2
11 |
18 |
19 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 浏览器窗口间通信
2 |
3 | 补充一下,这里的通讯指遵守同源策略情况下。
4 |
5 | -------
6 |
7 | 为了吸引读者的兴趣,先把demo放到前面:
8 | 下面有几个我自己写的演示**多页面通讯的demo**, 为了正常运行,请用最新的chrome浏览器打开。
9 | demo的源码地址[https://github.com/xiangwenhu/page-communication/tree/master/docs](https://github.com/xiangwenhu/page-communication/tree/master/docs)
10 |
11 | * [首页](https://xiangwenhu.github.io/page-communication/)
12 | * [setInterval + sessionStorage](https://xiangwenhu.github.io/page-communication/setInterval/index.html)
13 | * [localStorage](https://xiangwenhu.github.io/page-communication/localStorage/index.html)
14 | * [BroadcastChannel](https://xiangwenhu.github.io/page-communication/BroadcastChannel/index.html)
15 | * [SharedWorker](https://xiangwenhu.github.io/page-communication/SharedWorker/index.html)
16 |
17 | ------
18 |
19 | 为什么会扯到这个话题,最初是源于听 https://y.qq.com/ QQ音乐,
20 | * 播放器处于单独的一个页面
21 | * 当你在另外的一个页面搜索到你满意的歌曲的时候,点击播放或添加到播放队列
22 | * 你会发现,播放器页面做出了响应的响应
23 |
24 | 这里我又联想到了商城的购物车的场景,体验确实有提升。
25 | 刚开始,我怀疑的是Web Socket作妖,结果通过分析网络请求和看源码,并没有。 最后发现是localStore的storage事件作妖,哈哈。
26 |
27 | ------
28 | 回归正题,其实在一般正常的知识储备的情况下,我们会想到哪些方案呢?
29 |
30 | 1. ### WebSocket
31 | 这个没有太多解释,WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。当然是有代价的,需要服务器来支持。
32 | js语言,现在比较成熟稳定当然是 [socket.io](https://github.com/socketio/socket.io)和[ws](https://github.com/websockets/ws). 也还有轻量级的[ClusterWS](https://github.com/ClusterWS/ClusterWS)。
33 |
34 | 你可以在[The WebSocket API (WebSockets)
35 | ](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)看到更多的关于Web Socket的信息。
36 |
37 | 2. ### 定时器 + 客户端存储
38 |
39 | 定时器:setTimeout/setInterval/requestAnimationFrame
40 | 客户端存储: cookie/localStorage/sessionStorage/indexDB/chrome的FileSystem
41 |
42 | 定时器没啥好说的,关于客户端存储。
43 | * cookie: 每次会带到服务端,并且能存的并不大,4kb?,记得不太清楚
44 | * localStorage/sessionStorage 应该是5MB, sessionStorage关闭浏览器就和你说拜拜。
45 | * indexDB 这玩意就强大了,不过读取都是异步的,还能存 Blob文件,真的是很high。
46 | * chrome的FileSystem ,[Filesystem & FileWriter API](https://caniuse.com/#search=fileSystem),主要是chrome和opera支持。这玩意就是文件系统。
47 |
48 |
49 |
50 | 3. ### postMessage
51 | [Cross-document messaging](https://caniuse.com/#search=postMessage) 这玩意的支持率98.9%。 好像还能发送文件,哈哈,强大。
52 | 不过仔细一看 window.postMessage(),就注定了你首先得拿到window这个对象。 也注定他使用的限制, 两个窗体必须建立起联系。 常见建立联系的方式:
53 | * window.open
54 | * window.opener
55 | * iframe
56 |
57 | **提到上面的window.open, open后你能获得被打开窗体的句柄,当然也可以直接操作窗体了。**
58 |
59 | -------------------
60 |
61 | 到这里,我觉得一般的前端人员能想到的比较正经的方案应该是上面三种啦。
62 | 当然,我们接下来说说可能不是那么常见的另外三种方式。
63 |
64 |
65 | 1. ### StorageEvent
66 | Page 1
67 | ```js
68 | localStorage.setItem('message',JSON.stringify({
69 | message: '消息',
70 | from: 'Page 1',
71 | date: Date.now()
72 | }))
73 | ```
74 |
75 | Page 2
76 | ```js
77 | window.addEventListener("storage", function(e) {
78 | console.log(e.key, e.newValue, e.oldValue)
79 | });
80 | ```
81 | 如上, Page 1设置消息, Page 2注册storage事件,就能监听到数据的变化啦。
82 |
83 |
84 | 上面的e就是[StorageEvent](https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent),有下面特有的属性(都是只读):
85 | * key :代表属性名发生变化.当被clear()方法清除之后所有属性名变为null
86 | * newValue:新添加进的值.当被clear()方法执行过或者键名已被删除时值为null
87 | * oldValue:原始值.而被clear()方法执行过,或在设置新值之前并没有设置初始值时则返回null
88 | * storageArea:被操作的storage对象
89 | * url:key发生改变的对象所在文档的URL地址
90 |
91 |
92 | 5. ### Broadcast Channel
93 | 这玩意主要就是给多窗口用的,Service Woker也可以使用。 firefox,chrome, Opera均支持,有时候真的是很讨厌Safari,浏览器支持75%左右。
94 |
95 | 使用起来也很简单, 创建BroadcastChannel, 然后监听事件。 只需要注意一点,渠道名称一致就可以。
96 | Page 1
97 | ```js
98 | var channel = new BroadcastChannel("channel-BroadcastChannel");
99 | channel.postMessage('Hello, BroadcastChannel!')
100 | ```
101 | Page 2
102 | ```js
103 | var channel = new BroadcastChannel("channel-BroadcastChannel");
104 | channel.addEventListener("message", function(ev) {
105 | console.log(ev.data)
106 | });
107 | ```
108 |
109 | 6. ### SharedWorker
110 | 这是Web Worker之后出来的共享的Worker,不通页面可以共享这个Worker。
111 | MDN这里给了一个比较完整的例子[simple-shared-worker](https://github.com/mdn/simple-shared-worker)。
112 |
113 | 这里来个插曲,Safari有几个版本支持这个特性,后来又不支持啦,还是你Safari,真是6。
114 |
115 | 虽然,SharedWorker本身的资源是共享的,但是要想达到多页面的互相通讯,那还是要做一些手脚的。
116 | 先看看MDN给出的例子的ShareWoker本身的代码:
117 | ```js
118 | onconnect = function(e) {
119 | var port = e.ports[0];
120 |
121 | port.onmessage = function(e) {
122 | var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
123 | port.postMessage(workerResult);
124 | }
125 |
126 | }
127 | ```
128 | 上面的代码其实很简单,port是关键,这个port就是和各个页面通讯的主宰者,既然SharedWorker资源是共享的,那好办,把port存起来就是啦。
129 | 看一下,如下改造的代码:
130 | SharedWorker就成为一个纯粹的订阅发布者啦,哈哈。
131 | ```js
132 | var portList = [];
133 |
134 | onconnect = function(e) {
135 | var port = e.ports[0];
136 | ensurePorts(port);
137 | port.onmessage = function(e) {
138 | var data = e.data;
139 | disptach(port, data);
140 | };
141 | port.start();
142 | };
143 |
144 | function ensurePorts(port) {
145 | if (portList.indexOf(port) < 0) {
146 | portList.push(port);
147 | }
148 | }
149 |
150 | function disptach(selfPort, data) {
151 | portList
152 | .filter(port => selfPort !== port)
153 | .forEach(port => port.postMessage(data));
154 | }
155 |
156 | ```
157 |
158 |
159 | Broadcast
160 | >[MDN Web Docs - Broadcast Channel](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel)
161 | [BroadcastChannel | Can I Use](https://caniuse.com/#search=BroadcastChannel)
162 | [broadcast-channel](https://github.com/pubkey/broadcast-channel)
163 | BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers and NodeJ
164 | --------
165 |
166 | StorageEvent
167 | >[StorageEvent](https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent)
168 |
169 | ------
170 |
171 | SharedWorker
172 |
173 | >[SharedWorker](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker)
174 | [simple-shared-worker](https://github.com/mdn/simple-shared-worker/blob/gh-pages/worker.js)
175 | [SharedWorker | Can I Use](https://caniuse.com/#search=SharedWorker)
176 | [共享线程 SharedWorker](https://blog.csdn.net/qq_38177681/article/details/82048895)
177 | [feature-shared-web-workers](https://webkit.org/status/#feature-shared-web-workers)
178 | ------
179 |
180 |
181 | 其他
182 | >[两个浏览器窗口间通信总结](https://segmentfault.com/a/1190000016927268)
183 |
--------------------------------------------------------------------------------