Home

Web Components - Communication

Dec 15, 2023

Content

Communication Options for Web Components on the Same Page

If you're working with web components on the same page and want to establish communication between them without using any framework, consider the following options using plain JavaScript:

1. Local Storage or Session Storage:

Utilize localStorage or sessionStorage to store data that needs to be shared between web components on the same page. Components can set data in the storage, and others can read this data from the storage.

// Set data in one component localStorage.setItem('sharedData', 'Hello from Component A'); // Retrieve data in another component const sharedData = localStorage.getItem('sharedData'); // Handle the shared data here

2. PostMessage:

Use the window.postMessage method for communication between different web components on the same page. Components can send messages and listen for them within the same page.

// In one component window.postMessage({ type: 'customMessageType', data: 'Hello from Component B' }, window.location.origin); // In another component window.addEventListener('message', (event) => { if (event.data.type === 'customMessageType') { const receivedData = event.data.data; // Handle the received data here } });

3. Custom Events:

Leverage the built-in CustomEvent API to create and dispatch custom events. This allows one web component to notify others about specific actions or changes.

Example:

// In one component const event = new CustomEvent('myCustomEvent', { detail: { /* event data */ } }); this.dispatchEvent(event); // In another component this.addEventListener('myCustomEvent', (event) => { // Handle the event here });

Communication Options for Web Components on different pages (same domain)

If you're not using any framework and need a straightforward solution using plain JavaScript, several options are available for communication between web components on different pages:

1. Local Storage or Session Storage:

See part 1

2. PostMessage:

See part 1

3. Cookies:

Employ cookies to store small pieces of data that can be accessed by different pages on the same domain.

// Set a cookie in Component on Page A document.cookie = 'sharedCookie=Hello from Page A'; // Access the cookie in Component on Page B const cookies = document.cookie.split(';'); cookies.forEach((cookie) => { const [name, value] = cookie.trim().split('='); if (name === 'sharedCookie') { // Handle the shared data here in Component on Page B } });

4. BroadcastChannel:

Use the BroadcastChannel API to create a communication channel between different browsing contexts on the same origin. Components can send messages on one page and listen for them on another. Be

// Create a BroadcastChannel in Component on Page A const broadcastChannel = new BroadcastChannel('sharedChannel'); broadcastChannel.postMessage('Hello from Page A'); // Listen for messages in Component on Page B const broadcastChannel = new BroadcastChannel('sharedChannel'); broadcastChannel.onmessage = (event) => { const receivedData = event.data; // Handle the received data here in Component on Page B };

5. IndexedDB:

While typically used for more complex data storage scenarios, IndexedDB can be considered for sharing data between different pages.

// Set data in one component on Page A using IndexedDB const dbName = 'myDatabase'; const request = indexedDB.open(dbName, 1); request.onupgradeneeded = (event) => { const db = event.target.result; const objectStore = db.createObjectStore('sharedData', { keyPath: 'id' }); }; request.onsuccess = (event) => { const db = event.target.result; const transaction = db.transaction(['sharedData'], 'readwrite'); const objectStore = transaction.objectStore('sharedData'); const data = { id: 1, message: 'Hello from Page A' }; const addRequest = objectStore.add(data); addRequest.onsuccess = () => { // Data added successfully }; addRequest.onerror = (error) => { console.error('Error adding data:', error); }; }; // Retrieve data in another component on Page B using IndexedDB const dbName = 'myDatabase'; const request = indexedDB.open(dbName, 1); request.onsuccess = (event) => { const db = event.target.result; const transaction = db.transaction(['sharedData'], 'readonly'); const objectStore = transaction.objectStore('sharedData'); const getRequest = objectStore.get(1); getRequest.onsuccess = (event) => { const data = event.target.result; if (data) { // Handle the shared data here in Component on Page B console.log(data.message); // Output: Hello from Page A } }; getRequest.onerror = (error) => { console.error('Error retrieving data:', error); }; };

6. Shared Workers and Service Workers:

Shared Workers and Service Workers can be used for background processing and communication between pages, but they might be more complex for simple scenarios.

// shared-worker.js let sharedData = 'Hello from Shared Worker'; self.onconnect = (e) => { const port = e.ports[0]; port.onmessage = (event) => { sharedData = event.data; // Handle the shared data here console.log(sharedData); }; port.start(); }; // You can communicate with this worker from multiple components on different pages // Send a message to Shared Worker from Component on Page A const worker = new SharedWorker('shared-worker.js'); const port = worker.port; port.postMessage('New data from Page A'); // Send a message to Shared Worker from Component on Page B const worker = new SharedWorker('shared-worker.js'); const port = worker.port; port.postMessage('New data from Page B');

7. WebSockets:

Use WebSockets to establish a bidirectional communication channel between different pages, providing real-time capabilities.

// WebSocket server using Node.js (ws library) const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 3000 }); server.on('connection', (socket) => { socket.on('message', (message) => { // Handle the received data here console.log(`Received message: ${message}`); }); // Send a message to the connected clients socket.send('Hello from WebSocket Server!'); }); // Send a message to WebSocket Server from Component on Page A const socket = new WebSocket('ws://localhost:3000'); socket.onopen = () => { socket.send('New data from Page A'); }; // Send a message to WebSocket Server from Component on Page B const socket = new WebSocket('ws://localhost:3000'); socket.onopen = () => { socket.send('New data from Page B'); };

Choose the method that best fits the simplicity and requirements of your application. For many scenarios, localStorage, sessionStorage, or postMessage might be the most straightforward and widely supported solutions without the need for additional libraries or frameworks.

Made with ❤️ by Marouen Mhiri