0

I want to change the selected text in the foreground page from the background page of a Chrome extension, using insertHTML.

This works, and replaces the text in the foreground page with a bolded "test":

chrome.tabs.executeScript(
    null,
    {code: document.execCommand('insertHTML', false, "<b>test</b>")}, 
    res => callback(res)  //res => { alert(res[0]) });
    );

However, I cannot replace "test" with a variable.

I tried modifying the example in the MDN Web Docs: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript

var changeText = 'document.execCommand(\'insertHTML\', false, \"' + COMPARED_TEXT + '\")'; 
var executing = chrome.tabs.executeScript({
    code: changeText
  });

executing.then(onExecuted, onError);

I expected to be able to insert the value of COMPARED_TEXT, but the value of executing is undefined, and no error is thrown to say why.

Alex Russell
  • 189
  • 1
  • 10
  • 2
    You've tagged this question as a Chrome extension. `executing` is `undefined` because in Chrome extension, as mentioned in API docs, it does not return a Promise, but instead expects a callback. https://developer.chrome.com/extensions/tabs#method-executeScript – Gaurang Tandon Jul 02 '19 at 06:40
  • 1
    The `code` is a string so you can use the template strings substitution: \`document.execCommand('insertHTML', false, "${myVariable}")\` – wOxxOm Jul 02 '19 at 06:58

0 Answers0