I'm trying to pass a message from background script to the content script. My background script will make an ajax call with the user selected text and I want to replace the selected text with the ajax response. I have two problem to solve. The first problem is that I'm unable to pass a message from background script to the content script with this code: background.js
const doTranslation = (info, tab) => {
console.log(info, tab);
axios({
method: 'POST',
url: 'https://libretranslate.com/translate',
data: {
q: info.selectionText,
source: 'es',
target: 'en'
}
}).then( (res) => {
console.log(res.data.translatedText);
browser.tabs.query({active: true, currentWindow: true}, (tabs) => {
browser.tabs.sendMessage(tabs[0].id, {translation: res.data.translatedText});
});
});
}
The only console log I saw is the Hello from the content-script
but not the ajax response.
The second problem is about text replacing. How I can replace the selected text with the response?At the moment I have this code in content script
console.log('Hello from the content-script');
browser.runtime.onMessage.addListener( (message) => {
console.log(message);
});
UPDATE
I've found the problem, I wasn't declaring the tabs
permission to the manifest file and this caused the first issue about message passing from background to the content script. Now I'm trying to replace the text selection using the content script, any suggestion about?
browser.runtime.onMessage.addListener( (message) => {
console.log(message);
const selectedText = window.getSelection();
console.log(selectedText);
//replacing here
selectedText.replace(message);
});