Skip to content

Instantly share code, notes, and snippets.

@pierophp
Last active December 30, 2021 10:59
Show Gist options
  • Save pierophp/898f8316afa1bd04e04853bc3e3cfb48 to your computer and use it in GitHub Desktop.
Save pierophp/898f8316afa1bd04e04853bc3e3cfb48 to your computer and use it in GitHub Desktop.
Communication Between Tabs With Shared Worker
<html>
<body>
<a id="worker-message" href="javascript:void(0)">Send Message</a>
<script src="test.js"></script>
</body>
</html>
var connections = 0; // count active connections
var peers = [];
self.addEventListener("connect", function (e) {
var ports = e.ports;
var port = e.ports[0];
connections++;
peers.push({
connectionId: connections,
port: port
});
port.postMessage({
connectionId: connections,
type: 'CONNECTION'
});
port.addEventListener("message", function (e) {
peers.filter(function (peer) {
return peer.connectionId !== e.data.port;
}).forEach(function (peer) {
peer.port.postMessage(e.data);
});
});
port.start();
}, false);
var worker = new SharedWorker('sharedWorker.js');
var workerConnectionId;
worker.port.addEventListener('message', function (e) {
if (e.data.type == 'CONNECTION') {
workerConnectionId = e.data.connectionId
} else if (e.data.type == 'ALERT') {
alert('Ola ' + e.data.name);
}
});
worker.port.start();
document.getElementById('worker-message').onclick = function(){
worker.port.postMessage({
name: 'John',
type: 'ALERT',
port: workerConnectionId
});
};
@grinsteindavid
Copy link

thank u so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment