Home / Web Development / Exploring the Broadcast Channel API for cross-tab communication

Exploring the Broadcast Channel API for cross-tab communication

  1. In the notes-app directory, create a JavaScript file.

  2. Copy and paste the JavaScript code below into app.js.

    const noteList = document.getElementById("noteList");
    const noteInput = document.getElementById("noteInput");
    const addNoteButton = document.getElementById("addNoteButton");
    const resetNoteButton = document.getElementById("resetNoteButton");
    
    let notes = [];
    
    function renderNotes() {
      noteList.innerHTML = "";
    
      notes.forEach((note) => {
        const noteItem = document.createElement("div");
        noteItem.textContent = note;
        noteList.appendChild(noteItem);
      });
    }
    
    addNoteButton.addEventListener("click", () => {
      const newNote = noteInput.value.trim();
    
      if (newNote) {
        notes.push(newNote);
        renderNotes();
        noteInput.value = "";
    
        channel.postMessage({ action: "add", note: newNote });
      }
    });
    
    resetNoteButton.addEventListener("click", () => {
      notes = [];
      renderNotes();
    
      channel.postMessage({ action: "reset" });
    });
    
    const channel = new BroadcastChannel("notes-channel");
    
    channel.addEventListener("message", (event) => {
      const { action, note } = event.data;
    
      if (action === "add") {
        notes.push(note);
        renderNotes();
      } else if (action === "reset") {
        notes = [];
        renderNotes();
      }
    });
    
  3. Save and exit the file.

  4. Allow incoming connections to port 8080:

  5. Start a file server.

  6. Visit the application URL at http://:8080

Now you can open two browser windows or tabs side by side.
Add a note on one page in the application, and you will see that the note appears in the second tab without the need to refresh the page.
Try resetting all the notes, and you will see the notes get deleted from both the tabs without refreshing.

Let’s look at the code we have written in app.js. The renderNotes function creates an element for each note added.
The addNoteButton function allows us to add notes in the application, and channel.postMessage broadcasts the “add” action to other windows or tabs.
Similarly, resetNoteButton allows us to delete all existing notes, and channel.postMessage broadcasts the “reset action” to other windows or tabs.

At the end, a new BroadcastChannel is created with the name ‘notes-channel’, allowing communication between different windows/tabs that share the same origin.
The event listener for BroadcastChannel listens for message events from the channel and takes action according to the input provided.

Leave a Reply

Your email address will not be published. Required fields are marked *