'Bidirectional asynchronous messaging between website and extension popup

Use case:

  • website opens an extension popup window when a user clicks on a button
  • user performs some actions in the extension popup
  • a result of that action is sent back to the browser tab which initially opened the extension

Approach overview

(1) window.postMessage(data): Send a message to the content script where window.addEventListener("message", (event) => {...} is receiving the message event.

(2) chrome.runtime.sendMessage(event.data, function(response) {...}: This functionality is in the listener above and forwards the message to the background script where chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {...}) is receiving the message.

(3) Background scripts opens the extension as a dedicated popup window:

chrome.windows.getLastFocused().then((window) => {
    const width = 600 + 100;
    const height = 400 + 100;
    const left = window.width - width;
    chrome.windows.create({url: path, type: "popup", height: height, width: width, left: left, focused: true});
    });

(4) After having processed some user actions within the extension popup a response message should be returned to the content script:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {...})}

Problem

Everything works fine up to step (4). Because the extension popup has been opened programmatically as a dedicated popup window tabs[0].id contains a tab id from the extension popup window instead of the browser window which triggered the whole flow and where the content script runs.

  • How can the correct tab id be determined or forwarded along the chain to the popup?
  • Is this messaging scenario the right approach for my requirements?

Any feedback is very much appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source