addEventListener
Background
The addEventListener
function defines triggers for a Worker script to execute. There are currently three types of event listeners - "fetch"
listeners which are sent a FetchEvent
, "scheduled"
listeners which are sent a ScheduledEvent
and "queue"
listeners which are sent QueueEvent
.
Syntax
-
addEventListener(type, listener)
:void
- If multiple
"fetch"
listeners are registered, when one does not callevent.respondWith()
, the runtime delivers the event to the next registered listener. - A
"fetch"
listener,"scheduled"
listener, and"queue"
listener can be registered in the same script. - A script can have only one
"scheduled"
listener.
- If multiple
Parameters
-
type
string
- The only types supported are
"fetch"
,"scheduled"
and"queue"
.
- The only types supported are
-
listener
function
-
The function to handle incoming events to the Worker script. The listener is passed a single argument:
-
event
FetchEvent
orScheduledEvent
orQueueEvent
-
The events dispatched to a Worker. Refer to
FetchEvent
orScheduledEvent
.
-
Examples
Fetch Listener
addEventListener('fetch', event => {event.respondWith(new Response('Hello world'));});
Scheduled Listener
addEventListener('scheduled', event => {event.waitUntil(handleScheduled(event));});
Queue Listener
A Queue listener acts as a consumer for one or more queues.
addEventListener("queue", (event) => {event.waitUntil(handleMessages(event));});