Skip to content
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

addEventListener

Background

This 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 doesn’t call event.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.

Properties

  • type string
    • Currently the only types supported are "fetch" and "scheduled".
  • listener function

    • The function to handle incoming events to the Worker script. The listener is passed a single argument:

Examples

Fetch Listener

addEventListener("fetch", event => {  return event.respondWith(    new Response("Hello world")  )})

Scheduled Listener

addEventListener("scheduled", event => {  event.waitUntil(handleScheduled(event))})