3

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?

9
  • That error is to do with how the background and content scripts are communicating with each other, but you haven't added that code so we can't really debug it. Content scripts message the background script with runtime.sendMessage. Background scripts message the content scripts differently. Did my answer from a couple of days ago not help at all? Commented Oct 31, 2021 at 8:51
  • If you have a GH repo I'd be happy to take a look. Commented Oct 31, 2021 at 8:57
  • No, I'm testing the code locally. The thing is that the content script does not load at all. Only the background script loads. So communication is impossible in that case and the problem obviously has nothing to do with any possible errors with the messages between the scripts. The receiving end does not exist, because the content.js file that implements it does not load. Commented Oct 31, 2021 at 9:04
  • Ok, but I can't debug code that I have no access to. Commented Oct 31, 2021 at 9:09
  • Yes, I get that, but I don't think that's a problem of the code in the first place. The relative code that instructs Firefox to load the content script is part of the manifest.json file and I have shared the relative snippet. Probably there is nothing wrong with the manifest's code, so there is something else that prevents the script from loading. Commented Oct 31, 2021 at 9:19

1 Answer 1

1

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 });
  }
});
Sign up to request clarification or add additional context in comments.

8 Comments

Got there in the end though, didn't we? :)
You actually did to be honest. A million thanks!
FWIW it took me ages to write my first add-on. Write some code, look at the documentation, rewrite the code, look at the documentation again, write some new code etc. The API is confusing at first, but once you've created one you have a decent baseline for any more that you want to write. @Costas
Thanks for the encouragement! The last time I have coded for a Firefox extension was many years ago, when the XUL overlay was still used. The current code architecture looks more complicated to me, compared with the previous one, but you're right, everything is a matter of habit.
Here's something I wrote last week that allows me to add bespoke comments and code to SO comments and answers. The boilerplate for the add-on might help you in the future. It requires a new FF profile so I don't have to worry about the add-ons in my main profile, and that's called from ./rundev.sh in the terminal which is how I could fix your code so quickly. Anyway, good luck with the coding @Costas.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.