adele_yr
adele_yr

Reputation: 56

Why can't call chrome.runtime.sendMessage in chrome.tabs.onUpdated.addListener in chrome extension?

when I write below code and run it I got error:

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

worker.js:

async function createOffscreen() {
  if (await chrome.offscreen.hasDocument()) return;
  await chrome.offscreen.createDocument({
    url: "offscreen.html",
    reasons: ["AUDIO_PLAYBACK"],
    justification: "testing",
  });
}

chrome.runtime.onMessage.addListener(async (msg) => {
  switch (msg.type) {
    case "play":
      await createOffscreen();
      await chrome.runtime.sendMessage({
        type: "play",
        play: msg.play,
        offscreen: true,
      });
      break;
    case "pause":
      await createOffscreen();
      await chrome.runtime.sendMessage({ type: "pause", offscreen: true });
      break;
  }
});

chrome.tabs.onUpdated.addListener(
    function (tabId, changeInfo, tab) {
      chrome.runtime.sendMessage({ type: "pause", offscreen: true });
    }
    
)

I want to send message when the url changed, does there have any other methods to do it?

Upvotes: 1

Views: 814

Answers (1)

Oliver Dunk
Oliver Dunk

Reputation: 524

I think this might be an issue where your onUpdated listener is trying to send a message, but it has nowhere to send that message to. The solution would depend on what you're trying to do:

  • If you're trying to send the pause message to the offscreen document, you'll want to make sure to create it first. Your onUpdated doesn't currently have any logic for this.
  • If you're trying to communicate between two parts of your background service worker, maybe consider events or just directly calling functions instead?

Upvotes: 2

Related Questions