addEventListener
Background
The addEventListener
function defines triggers for a Worker script to execute. There are currently two types of event listeners - "fetch"
listeners which are sent a FetchEvent
and "scheduled"
listeners which are sent a ScheduledEvent
.
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 and a"scheduled"
listener can be registered in the same script. - A script can have only one
"scheduled"
listener.
- If multiple
Properties
type
string
- The only types supported are
"fetch"
and"scheduled"
.
- 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
- The events dispatched to a Worker. Refer to
FetchEvent
orScheduledEvent
.
- The events dispatched to a Worker. Refer to
Examples
Fetch Listener
addEventListener('fetch', event => { event.respondWith(new Response('Hello world'));
});
Scheduled Listener
addEventListener('scheduled', event => { event.waitUntil(handleScheduled(event));
});