shiichan

Workers Event and EventTarget Get Closer to the Web Spec!

Hi, it's Shii-chan!

Cloudflare Changelog developers.cloudflare.com

Today's news is about Workers events moving closer to browser behavior.

What was announced?

The Cloudflare Changelog announced that the Workers runtime's Event, EventTarget and related APIs are now closer to their web platform specifications.

There are five changes:

  • isTrusted is now correct
  • on<type> handlers fire in registration order
  • MessageEvent constructor improvements
  • CloseEvent and ErrorEvent constructor improvements
  • MessagePort starts when you add a message listener

The story so far

Some behavior used to differ from the specs:

  • User-constructed events incorrectly reported isTrusted as true
  • onmessage, onabort and similar handlers always fired before addEventListener() listeners, no matter when they were assigned
  • A MessagePort only started when you assigned onmessage

What changes

Code written for browsers, and libraries that assume spec-compliant behavior, should be more likely to work as expected on Workers!

Dive Deep

isTrusted

User-constructed events such as new MessageEvent(...), new CustomEvent(...), new ErrorEvent(...) and new CloseEvent(...) now report isTrusted as false.

Handler ordering

Event handler attributes such as onmessage and onabort now fire in registration order relative to addEventListener() calls, just like in browsers.

Constructors

  • new MessageEvent(type) works without an init object, and data defaults to null per spec
  • MessageEventInit now supports origin, lastEventId, source and ports in addition to data
  • CloseEventInit and ErrorEventInit accept the standard EventInit members bubbles, cancelable and composed

MessagePort

Adding a listener with addEventListener("message", ...) now starts the port.

Wrap-up

  • isTrusted is false for user-constructed events
  • on<type> handlers fire in registration order
  • MessageEvent, CloseEvent and ErrorEvent constructors are closer to the spec
  • A MessagePort starts once you add a message listener

This is for anyone sharing code between browsers and Workers, or porting event-heavy libraries!