Last active
December 30, 2021 10:59
-
-
Save pierophp/898f8316afa1bd04e04853bc3e3cfb48 to your computer and use it in GitHub Desktop.
Communication Between Tabs With Shared Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<a id="worker-message" href="javascript:void(0)">Send Message</a> | |
<script src="test.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank u so much!