files/en-us/web/api/sharedworkerglobalscope/connect_event/index.md
{{APIRef("Web Workers API")}}
The connect event is fired in shared workers at their {{domxref("SharedWorkerGlobalScope")}} when a new client connects.
This event is not cancelable and does not bubble.
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
addEventListener("connect", (event) => { })
onconnect = (event) => { }
A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MessageEvent")}}
This interface also inherits properties from its parent, {{domxref("Event")}}.
MessageEventSource (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter.This example shows a shared worker file — when a connection to the worker occurs from a main thread via a {{domxref("MessagePort")}}, the onconnect event handler fires. The event object is a {{domxref("MessageEvent")}}.
The connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postMessage() method can be used to send messages back to the main thread using the worker.
self.onconnect = (e) => {
const port = e.ports[0];
port.onmessage = (e) => {
const workerResult = `Result: ${e.data[0] * e.data[1]}`;
port.postMessage(workerResult);
};
port.start();
};
For a complete running example, see our Basic shared worker example (run shared worker.)
You could also set up an event handler using the {{domxref("EventTarget/addEventListener", "addEventListener()")}} method:
self.addEventListener("connect", (e) => {
const port = e.ports[0];
port.onmessage = (e) => {
const workerResult = `Result: ${e.data[0] * e.data[1]}`;
port.postMessage(workerResult);
};
});
{{Specifications}}
{{Compat}}