Shared Worker 与普通的 Web Worker 类似,但不同之处在于它可以被多个浏览器窗口、标签页或者iframe共享,使得这些上下文之间能够相互通信。下面是一个使用 Shared Worker 的完整示例。
共享Worker脚本(sharedWorker.js)
self.addEventListener('connect', function(event) {
var port = event.ports[0];
port.onmessage = function(e) {
console.log('Received message:', e.data);
if (e.data.type === 'broadcast') {
port.postMessage({ type: 'broadcast', data: e.data.message, origin: e.origin });
} else if (e.data.type === 'ping') {
port.postMessage({ type: 'pong', data: 'Pong from Shared Worker!', origin: e.origin });
}
};
port.start();
port.postMessage({ type: 'ready', message: 'Shared Worker is ready!', origin: location.origin });
});
HTML 页面1(page1.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page 1</title>
</head>
<body>
<h2>Page 1</h2>
<button onclick="sendPing()">Ping Shared Worker</button>
<div id="response"></div>
<script>
if (navigator.userAgent.indexOf("Trident") !== -1) {
alert("Internet Explorer does not support Shared Workers.");
} else {
var worker = new SharedWorker('sharedWorker.js');
worker.port.start();
worker.port.onmessage = function(e) {
if (e.data.type === 'ready') {
document.getElementById('response').innerText = e.data.message;
} else if (e.data.type === 'pong') {
document.getElementById('response').innerText = 'Received: ' + e.data.data;
} else if (e.data.type === 'broadcast') {
document.getElementById('response').innerText += '\nBroadcast from ' + e.data.origin + ': ' + e.data.data;
}
};
function sendPing() {
worker.port.postMessage({ type: 'ping', message: 'Ping from Page 1' });
}
}
</script>
</body>
</html>
HTML 页面2(page2.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page 2</title>
</head>
<body>
<h2>Page 2</h2>
<button onclick="broadcastMessage()">Broadcast Message</button>
<div id="response"></div>
<script>
if (navigator.userAgent.indexOf("Trident") !== -1) {
alert("Internet Explorer does not support Shared Workers.");
} else {
var worker = new SharedWorker('sharedWorker.js');
worker.port.start();
worker.port.onmessage = function(e) {
if (e.data.type === 'ready') {
document.getElementById('response').innerText = e.data.message;
} else if (e.data.type === 'broadcast') {
document.getElementById('response').innerText += '\nBroadcast from ' + e.data.origin + ': ' + e.data.data;
}
};
function broadcastMessage() {
var message = prompt("Enter a message to broadcast:");
if (message) {
worker.port.postMessage({ type: 'broadcast', message: message });
}
}
}
</script>
</body>
</html>
在这个例子中,sharedWorker.js
作为一个Shared Worker,能够接收来自多个页面的消息,并根据消息类型执行不同的操作。page1.html
可以向Shared Worker发送ping请求并接收pong响应,同时也能接收其他页面通过Worker广播的消息。page2.html
则可以输入消息并广播给所有连接到该Shared Worker的页面。这样,多个页面可以通过Shared Worker实现数据的共享和通信。