1

I have a tab change listener in background script which which will send a message to the content script to preform a set of actions in content script.

My code in background script is

window.chrome.tabs.onActivated.addListener((activeInfo) => {
  window.chrome.tabs.sendMessage(activeInfo.tabId, { type: 'getLibraries' }, (data) => {
      // do some thing
    });
});

content script is

window.chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message.type) {
    case 'getLibraries':
      // do something
      break;
    default:
      console.error('Unrecognised message: ', message);
  }
});

This is working fine in most cases. When I add the extension to my browser and switch to a previously opened tab, the content script wont be present there as the plugin was not present while loading the tab. At this time the background scrip tries to send message on tab change. Since there is no content script chrome will throw the following error

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist

I need a tab change detection in background script which will send a message to the content script without causing the above error. Is there any way to detect if the content script has loaded from background script?

Karthik
  • 1,332
  • 1
  • 12
  • 21
  • The error message means there's no tab with that `tabId`. Show us how `tabId` is defined. Also if your "content_scripts" section of manifest.json doesn't have "run_at":"document_start" then add it and reload the extension. – wOxxOm Nov 03 '19 at 15:41
  • Sorry I have updated the question. It should be with the tabId `activeInfo.tabId`. Will try with "run_at":"document_start". – Karthik Nov 03 '19 at 15:47
  • 1
    Ah, I didn't read the question fully. The problem is that Chrome doesn't inject your content scripts on installation/update so you need to do it manually: [more info](/a/11598753) – wOxxOm Nov 03 '19 at 15:51
  • Thanks i was able to figure it out with the info you shared – Karthik Nov 03 '19 at 18:21

0 Answers0