Home > Software design >  Firefox extension content script does not load during temporary add-on load
Firefox extension content script does not load during temporary add-on load

Time:11-01

I'm developing an extension that involves both a background script and a content script. The content script gets the selected text from webpages, when the user clicks on the extension's relative menu entry and then sends it to the background script for further processing.

Here is the relative section of the manifest.json:

"background": {
    "scripts": ["background.js"]
  },
  
  "content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content.js"]
  }
]

I load the extension in about:debugging > This Firefox > Load Temporary Add-on... in order to test it.

In the code I send a message from the background script to the content script but that throws an error:

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

I checked by using the Debugger, in about:devtools-toolbox and I found out that only the background script loads.

Does anyone have an idea what makes the content script to fail to load and what would the solution be?

CodePudding user response:

The background script should send a message to the content script, asking for the selected text, and then listen to the message it receives. Then it can call the function that does the Google search:

function onCreated() {
  if (browser.runtime.lastError) {
    console.log(`Error: ${browser.runtime.lastError}`);
  } else {
    console.log("Item created successfully");
  }
}

browser.menus.create({
  id: "context-entry",
  title: 'search',
  contexts: ['all'],
  onclick: getText
}, onCreated);

async function getText() {
  const tabInfo = await getCurrentTab();
  const [{ id: tabId }] = tabInfo;
  browser.tabs.sendMessage(tabId, { trigger: 'getText' });
}

browser.runtime.onMessage.addListener(function ({ txt }) {
  doSearch(txt);
});

function doSearch(txt) {
  var searchURL = `https://www.google.com/search?q=${txt}`;
  browser.tabs.create({url: searchURL});
}

And the content script should listen to the message from the background script, and send the selected text back.

browser.runtime.onMessage.addListener(({ trigger }) => {
  if (trigger === 'getText') {
    const selection = window.getSelection();
    const txt = selection.toString();
    browser.runtime.sendMessage({ trigger: 'foundText', txt });
  }
});
  • Related