In Chrome and Firefox <57 it works, but in Firefox Quantum doesn't work.
The goal is to send a message to another tab in the browser.
When filling in the text input and clicking the send button, the other tab in the browser should write the message in the browser console.
html file:
<script type="text/javascript">
const myWorker = new SharedWorker( "sharedWorkerChat.js" );
const port = myWorker.port;
port.addEventListener( "message", function( e ) {
console.log( e.data );
}, false );
port.start();
function postMessage() {
const value = document.getElementById( "input" ).value;
console.log( value );
port.postMessage( value );
}
</script>
<input type="text" id="input" />
<button onclick="postMessage()"> Send </button>
sharedWorkerChat.js
var m;
var instances = [];
self.addEventListener( "connect", function ( e ) {
var port = e.ports[ 0 ];
instancias.push( port );
port.addEventListener( "message", function ( message ) {
m = message.data;
instances.forEach( function( p ) {
p.postMessage( m );
});
}, false );
port.start();
}, false);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…