实现多个标签页之间通信的sharedworker
2018-12-14 本文已影响0人
AAA前端
不多逼逼,直接上代码
- 首先在服务器上要有一个js,处理需要通信的数据。比如一个worker.js
let data = ''
onconnect = function (e) {
let port = e.ports[0]
port.onmessage = function (e) {
if (e.data === 'get') { // 如果是get 则返回数据给客户端
port.postMessage(data)
} else { // 否则把数据保存
data = e.data
}
}
}
- A页面负责传递数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<button>点击</button>
<body>
<script>
if (typeof Worker === "undefined") {
alert('当前浏览器不支持webworker')
} else {
let worker = new SharedWorker('worker.js')
window.worker = worker
var i = 0;
document.querySelector('button').onclick = function() {
window.worker.port.postMessage('发送信息给worker' + i++)
}
}
</script>
</body>
</html>
- B页面 就可以获取数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<button>获取</button>
<body>
<script>
// 这段代码是必须的,打开页面后注册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'表示获取数据。
document.querySelector('button').onclick = function() {
window.worker.port.postMessage('get')
}
</script>
</body>
</html>