Home > Back-end >  What's the best way to call a content scripts' function from the background script in a Fi
What's the best way to call a content scripts' function from the background script in a Fi

Time:11-06

I want to call a function that is implemented in the content script of an extension, that gets the selected text from webpages, from a function in the background script that will be later called in a listener connected to a menu item.

Is that possible and what would be the shortest way to do it?

Here are the relevant code snippets:

manifest.json

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

content.js

var text = "";
    
function highlightedText() {
  text = content.getSelection();
}

background.js

function listenerFunction() {

    highlightedText();
    
    /* Doing various stuff that have to use the text variable */
  }
  
    browser.menus.onClicked.addListener((info, tab) => {
    highlightedText();
  });

Obviously, the above code is not working as the "highlighted" function is now visible from the background script.

So, what's the quickest / shortest way to make the code work?

CodePudding user response:

OK. I'm having to crib this from one of my own private extensions but the gist is this:

In the background script set up the menu, and assign a function to the onclick prop:

browser.menus.create({
  id: 'images',
  title: 'imageDownload',
  contexts: ['all'],
  onclick: downloadImages
}, onCreated);

Still in the same script get the current tab information, and send a message to the content script.

function getCurrentTab() {
  return browser.tabs.query({ currentWindow: true, active: true });
}

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

The content script listens for the message:

browser.runtime.onMessage.addListener(({ trigger }) => {
  if (trigger === 'downloadImages') doSomething();
});

And once the processing is done pass a new message back to the background script.

function doSomething() {
  const data = [1, 2, 3];
  browser.runtime.sendMessage({ trigger: 'downloadImages', data });
}

And in a separate background script I have the something like the following:

browser.runtime.onMessage.addListener(function (data) {
  const { trigger } = data;
  if (trigger === 'downloadImages') ...
});
  • Related