Harnessing the Power of Messagechannel and Broadcastchannel

Rate this content
Bookmark

Delve into the world of Web API's - MessageChannel and BroadcastChannel. Explore how these powerful APIs facilitate seamless communication in web workers, iframes, and across tabs. Join us as we uncover the techniques to enhance web interactions and unlock new possibilities. Discover the key to smoother collaboration and improved connectivity in your web projects!

This talk has been presented at React Advanced Conference 2023, check out the latest edition of this React Conference.

Watch video on a separate page

FAQ

The basic method discussed by Daniel Jakobsen for communicating between iframes involves using the postMessage API. This API allows messages to be sent between the main page and the embedded iframe, facilitating communication between web components.

The disadvantages of using the naive postMessage approach include difficulty in implementing promise support, limitation to direct communication only (between the parent or top window and the iframe), and potential pollution of the global event handler which can lead to security concerns and computational overhead.

The Message Channel API provides a more structured way of communication between web components by using two linked message ports. This setup allows for secure and direct data transfer between components without the data being exposed to the global scope, thereby reducing the risk of interference from other scripts.

In the Message Channel API, when a message channel is created, it generates two connected ports, port1 and port2. Messages sent from port1 can be received by port2 and vice versa. This channel ensures that communication is direct and not exposed to the global environment, enhancing security and data integrity.

The Message Channel Shake library is designed to simplify the implementation of the Message Channel API by reducing boilerplate code and facilitating easier setup for bidirectional communication, promise support, and integration with frameworks like React for iframes and web workers.

The Message Channel Shake library integrates with React through a provider component and hooks. It wraps the React app with a 'MessageChannelShakeProvider' and uses 'IframeChannelWrapper' for iframe integration and 'usePortMessenger' hook within the iframe to enable message passing and handling as promises.

Daniel Jakobsen
Daniel Jakobsen
11 min
23 Oct, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This talk explores hidden web APIs for communicating between iframes and web workers. It discusses the disadvantages of a naive messaging approach and introduces the message channel API as a solution. The speaker also presents a library called message-channel-shake that simplifies message channel implementation. The talk covers various technologies like React, broadcast channel, and transferable objects.

1. Introduction to Web Messaging

Short description:

Welcome to this talk about web messaging. I'm Daniel Jakobsen, a full-stack staff engineer at Vim. We'll explore hidden web APIs for communicating between iframes and web workers. We'll start with a naive messaging example and then dive into message channel-based messaging using the message channel API.

Hello, everybody. Welcome to this talk about web messaging. I'm Daniel Jakobsen. I'm a full-stack staff engineer at Vim. Not the editor. It's a different company. We do healthcare.

We've encountered many problems that we needed to communicate between iframes and web workers and I wanted to share with you some of the insights we have found and really some hidden web APIs that are not that known that you can leverage and can really help you with communicating between these web components.

So what are we going to learn? We're going to start with a naive messaging example with iframes just to see how we can communicate between them with really the basic building blocks. And then we're going to deep dive a bit into message channel-based messaging. We're going to leverage something that's called message channel API. It's a browser API that's been here for a long, long time, but it's not that known, at least it wasn't for me. And, yeah, we're going to see this basic demo.

2. Naive Communication Example

Short description:

We have a naive communication example where an embedded iframe sends a message to the main page. The main HTML waits for the iframe to load and then uses postMessage to send a payload. The embedded iframe receives the message and verifies its origin before sending a response back to the parent page.

We have here a naive communication example. We have the main site and inside it, there is an embedded iframe. And we can see that we have the message back from the iframe. This is the message that the iframe is sending, and inside the embedded iframe there is a hello from the main page. So let's see how that's going to work.

So this is the main HTML. And inside here, with the first thing we do is we wait for the embedded iframe to load. Once that occurs, we use postMessage. PostMessage is the most basic building block of communication. It allows us to send messages to iframes, web workers, most web components in the browser support postMessage. And here that's exactly what we do, we take the iframe element and we use postMessage, we send some payload and we're going to see in a moment how the embedded iframe receives this message.

So this is the embedded iframe HTML page, and inside here we have an adEventListener, it's a global adEventListener in the window, and we are listening to message event, and the previous postMessage comes directly, one more, comes directly to here, and inside here is a logic to verify that the message comes from the main page, because there could be multiple messages that come here. We do some logic, and then we use yet again the postMessage, but this time the embedded iframe does the postMessage on the parent page. So in the window.parent there is also window.top that you can do postMessage and it works the same way around. Now in the main html page we have the global event listener. We can handle the logic and do some whatever we want.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Install Nothing: App UIs With Native Browser APIs
JSNation 2024JSNation 2024
31 min
Install Nothing: App UIs With Native Browser APIs
This Talk introduces real demos using HTML, CSS, and JavaScript to showcase new or underutilized browser APIs, with ship scores provided for each API. The dialogue element allows for the creation of modals with minimal JavaScript and is supported by 96% of browsers. The web animations API is a simple and well-supported solution for creating animations, while the view transitions API offers easy animation workarounds without CSS. The scroll snap API allows for swipers without JavaScript, providing a smooth scrolling experience.
Pushing the Limits of Video Encoding in Browsers With WebCodecs
JSNation 2023JSNation 2023
25 min
Pushing the Limits of Video Encoding in Browsers With WebCodecs
Top Content
This Talk explores the challenges and solutions in video encoding with web codecs. It discusses drawing and recording video on the web, capturing and encoding video frames, and introduces the WebCodecs API. The Talk also covers configuring the video encoder, understanding codecs and containers, and the video encoding process with muxing using ffmpeg. The speaker shares their experience in building a video editing tool on the browser and showcases Slantit, a tool for making product videos.
Visualising Front-End Performance Bottlenecks
React Summit 2020React Summit 2020
34 min
Visualising Front-End Performance Bottlenecks
React's web-based tools allow for independent learning. Dazzone, a sports streaming service, faces challenges with low memory and CPU targets. Measuring, analyzing, and fixing performance issues is crucial. Virtualization improves rendering efficiency and performance. The application is now much faster with significantly less jank.
WebHID API: Control Everything via USB
JSNation 2022JSNation 2022
23 min
WebHID API: Control Everything via USB
Today's Talk introduces the webHID API, which allows developers to control real devices from the browser via USB. The HID interface, including keyboards, mice, and gamepads, is explored. The Talk covers device enumeration, input reports, feature reports, and output reports. The use of HID in the browser, especially in Chrome, is highlighted. Various demos showcase working with different devices, including a DualShock controller, microphone, gamepad, and Stream Deck drum pad. The Talk concludes with recommendations and resources for further exploration.
Automate the Browser With Workers Browser Rendering API
JSNation 2024JSNation 2024
20 min
Automate the Browser With Workers Browser Rendering API
The Talk discusses browser automation using the Worker's Browser Rendering API, which allows tasks like navigating websites, taking screenshots, and creating PDFs. Cloudflare integrated Puppeteer with their workers to automate browser tasks, and their browser rendering API combines remote browser isolation with Puppeteer. Use cases for the API include taking screenshots, generating PDFs, automating web applications, and gathering performance metrics. The Talk also covers extending sessions and performance metrics using Durable Objects. Thank you for attending!
MIDI in the Browser... Let's Rock the Web!
JSNation 2022JSNation 2022
28 min
MIDI in the Browser... Let's Rock the Web!
MIDI is a versatile communication protocol that extends beyond music and opens up exciting possibilities. The Web MIDI API allows remote access to synths and sound modules from web browsers, enabling various projects like music education systems and web audio-based instruments. Developers can connect and use MIDI devices easily, and the Web MIDI API provides raw MIDI messages without semantics. The WebMidi.js library simplifies working with the Web MIDI API and offers a user-friendly interface for musicians and web developers. MIDI on the web has generated significant interest, with potential for commercial growth and endless possibilities for web developers.

Workshops on related topic

Writing Universal Modules for Deno, Node and the Browser
Node Congress 2022Node Congress 2022
57 min
Writing Universal Modules for Deno, Node and the Browser
Workshop
Luca Casonato
Luca Casonato
This workshop will walk you through writing a module in TypeScript that can be consumed users of Deno, Node and the browsers. I will explain how to set up formatting, linting and testing in Deno, and then how to publish your module to deno.land/x and npm. We’ll start out with a quick introduction to what Deno is.