ShareWorker和Worker区别
worker:专属线程,只针对当前运行环境(HTML 5 Web Workers)
sharedWorker:共享线程,同源策略下,多个运行环境共用同一个线程,包括数据。
方法
- start:开启连接
- connect:连接
- postMessage:发送数据
- onmessage:接收数据
页面通信举例
页面
<body>
<input type="text" id="input">
<button id="submit">提交</button>
<p id="news"></p>
</body>
<script>
let work = new SharedWorker('work.js');
let port = work.port;
//开启
port.start();
//通知所有人
port.postMessage({ type: "start" });
//点击触发事件
submit.onclick = function (e) {
port.postMessage({
type: "msg",
value: input.value
});
input.value = "";
}
//接收数据
port.onmessage = function (e) {
console.log(e.data)
if (Array.isArray(e.data)) {
let html = "";
e.data.forEach(msg => {
html += `<p>${msg}</p>`;
});
news.innerHTML = html;
} else {
news.innerHTML = e.data;
}
}
</script>
work.js
let connectList = [], msgList = [];
self.onconnect = function (w) {
// 开启
let port = w.ports[0];
port.start();
// 监听
port.onmessage = function (e) {
let worker = e.currentTarget, data = e.data;
// 加入到列表
if (connectList.indexOf(worker) === -1) {
connectList.push(worker);
}
//新用户进入
if (data.type === "start") {
connectList.forEach(item => {
if (item === worker)
item.postMessage("你已进入");
else
item.postMessage("新用户进入");
})
}
//新消息
if (data.type === "msg") {
msgList.push(data.value);
connectList.forEach(item => {
item.postMessage(msgList);
})
}
}
}