Core JavaScript

Shared Worker with Messaging

This example demonstrates how to create a shared worker with message passing back and forth in JavaScript.

SharedWorkerMessaging.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>XoaX.net's Workers Demo</title>
		<script type="text/javascript">
			function Initialization() { 
				var qSharedWorker = new SharedWorker("SharedWorkerMessaging.js");
				var qOutput = document.getElementById('idOutput');
				qSharedWorker.port.addEventListener('message', function(e) {
					qOutput.textContent  += e.data;
				});
				// Required for addEventListener
				qSharedWorker.port.start();
				qSharedWorker.port.postMessage('XoaX.net');
			}
		</script>
		<style type="text/css">
			#idOutput {
				color: lime;
				background-color: black;
				border: 1px solid black;
				padding: 5px;
				margin: 5px;
				float: left;
			}
		</style>
	</head>
	<body onload="Initialization()">
		<pre id="idOutput">Received: </pre>
	</body>
</html>

SharedWorkerMessaging.js

// NOTE: THIS REQUIRES A WEB SERVER TO RUN
onconnect = function(e) {
	var qPort = e.ports[0];
	qPort.postMessage('Hello from worker!\n');
	qPort.onmessage = function(e) {
		e.target.postMessage('Message received from main and sent back: ' + e.data);
	}
}
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.