实现多个标签页之间通信的几种方法(sharedworker)

2021-10-11  本文已影响0人  小豆soybean

原文链接:https://www.cnblogs.com/cangqinglang/p/10635707.html

image

prologue

localstorage

<pre style="margin: 0px; padding: 0px; overflow: auto; font-family: "Courier New"; font-size: 12px; overflow-wrap: break-word;">window.onstorage = (e) => {console.log(e)} // 或者这样
window.addEventListener('storage', (e) => console.log(e))</pre>

webworker

SharedWorker

[ 复制代码

](javascript:void(0); "复制代码")

<pre style="margin: 0px; padding: 0px; overflow: auto; font-family: "Courier New"; font-size: 12px; overflow-wrap: break-word;">// sharedWorker所要用到的js文件,不必打包到项目中,直接放到服务器即可
let data = '' onconnect = function (e) {
let port = e.ports[0]

port.onmessage = function (e) { if (e.data === 'get') {
port.postMessage(data)
} else {
data = e.data
}
}
}</pre>

[ 复制代码

](javascript:void(0); "复制代码")

[ 复制代码

](javascript:void(0); "复制代码")

<pre style="margin: 0px; padding: 0px; overflow: auto; font-family: "Courier New"; font-size: 12px; overflow-wrap: break-word;">// 这段代码是必须的,打开页面后注册SharedWorker,显示指定worker.port.start()方法建立与worker间的连接
if (typeof Worker === "undefined") {
alert('当前浏览器不支持webworker')
} else {
let worker = new SharedWorker('worker.js')
worker.port.addEventListener('message', (e) => {
console.log('来自worker的数据:', e.data)
}, false)
worker.port.start()
window.worker = worker
} // 获取和发送消息都是调用postMessage方法,我这里约定的是传递'get'表示获取数据。
window.worker.port.postMessage('get')
window.worker.port.postMessage('发送信息给worker')</pre>

[ 复制代码

](javascript:void(0); "复制代码")

上一篇下一篇

猜你喜欢

热点阅读