Broadcasting events and communicating state

Last updated: December 8, 2024

Because Web Fragments are encapsulated in a custom element shadowRoot, they are part of the same Document Object Model and can leverage Web Platform APIs. This makes Web Fragments future-proof and agnostic, and reduces maintenance efforts.

Our team is currently working with standards bodies to push parts of the Web Fragments to the Web Platform as standards.

Using Broadcast Channel to communicate between fragments

Fragments can share data using the Broadcast Channel API to post messages and share state.

Broadcasting scenario example

Assume a catalog or product list as a first fragment and a shopping cart as a second fragment. When items are added to the cart using a button in the product list, the cart gets a message from the catalog.

// fragment A - post (broadcast) message
const bc = new BroadcastChannel('/cart');
bc.postMessage({ type: 'cart_cleared' });
bc.close();
// fragment B - listen and process message
const handleMessage = (event: MessageEvent) => {
  const { type, product } = event.data;
  if (type === 'add_to_cart') {
    addItem(product);
  }
};

const bc = new BroadcastChannel("/cart");
bc.addEventListener('message', handleMessage);

return () => {
  bc.removeEventListener('message', handleMessage);
};

web fragments middleware

Please note that all fragments should share the same origin.