Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
Can web workers share data directly with the main thread without using postMessage in JavaScript? Pending Review
Asked on Jan 15, 2026
Answer
Web Workers cannot share data directly with the main thread without using "postMessage". They communicate by sending messages back and forth using the "postMessage" method and the "onmessage" event handler.
<!-- BEGIN COPY / PASTE -->
// Main thread
const worker = new Worker('worker.js');
worker.postMessage('Hello from main thread');
worker.onmessage = function(event) {
console.log('Received from worker:', event.data);
};
// worker.js
self.onmessage = function(event) {
console.log('Received from main thread:', event.data);
self.postMessage('Hello from worker');
};
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- Web Workers operate in a separate global context and cannot access the DOM or variables in the main thread directly.
- Data is passed between the main thread and workers using "postMessage", which serializes the data.
- For complex data, consider using "Transferable Objects" to transfer ownership of data between threads efficiently.
- Always ensure that the worker script is served from the same origin or is CORS-enabled.
Recommended Links:
