SharedWorker

This commit is contained in:
2023-11-12 04:13:05 +08:00
parent 05c3507631
commit ce943faa6e
5 changed files with 137 additions and 2 deletions

18
src/main.js Normal file
View File

@@ -0,0 +1,18 @@
if (typeof SharedWorker === "undefined") {
alert('当前浏览器不支持webworker')
}
// 检查是否存在其它标签页, 如果存在不必建立 websocket 连接, 如果不存在, 则建立 websocket 连接
const worker = new SharedWorker('/src/worker.js')
worker.port.onmessage = (e) => {
console.log('worker.port.onmessage:', e.data)
}
worker.port.start()
const button = document.createElement('button')
button.innerText = 'click'
button.onclick = () => {
worker.port.postMessage('hello, worker')
}
document.body.appendChild(button)

42
src/worker.js Normal file
View File

@@ -0,0 +1,42 @@
const ports = []
self.onconnect = (e) => {
console.log('worker.onconnect:', e)
for (const port of e.ports) {
port.onmessage = (e) => {
console.log('onmessage:', ports)
ports.forEach(item => {
item.postMessage(e.data)
})
}
port.onclose = () => {
console.log('onclose:', ports)
var index = ports.indexOf(port)
if (index !== -1) {
ports.splice(index, 1)
}
}
ports.push(port)
}
}
//// 获取当前浏览器是 http 还是 https 以判断使用 ws 还是 wss
//const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
//const host = window.location.host
//
//// 向服务器建立 websocket 连接
//const ws = new WebSocket(`${protocol}://${host}/online?name=client`)
//ws.onopen = () => {
// console.log('ws.onopen')
//}
//ws.onclose = () => {
// console.log('ws.onclose')
//}
//ws.onerror = () => {
// console.log('ws.onerror')
//}
//ws.onmessage = message => {
// console.log('ws.onmessage:', message)
// const data = JSON.parse(message.data)
// console.log('message:', data)
//}