chorme extension - How to replace user selected text

Viewed 33

I'm working on a translate chrome extension. I want to get the user selection and translate it after the user click on a context menu voice. I've implemented this code but not work as expected. I've tested it on instagram and seems working into the DM input field. The same code will not work as expected with facebook text input for messages or status textarea. How I can manage the selected text replacing after that it's translated?

background.js

const processSelection = (info, tab) => {
  axios({
    method: 'GET',
    url: 'https://translate.googleapis.com/translate_a/single',
    params: {
      client: 'gtx',
      sl: 'auto',
      tl: 'en',
      dt: 't',
      q: info.selectionText
    }
  }).then( (res) => {
    browser.tabs.sendMessage(tab.id, {translation: res.data[0][0][0]});
  });
}

browser.contextMenus.create({
  id: 'selection-translate',
  title: 'Translate selection',
  contexts: ['editable','selection']
});

browser.contextMenus.onClicked.addListener(processSelection);

content-script.js

browser.runtime.onMessage.addListener( (message) => {
    console.log(message);
    const selectedText = window.getSelection();
    const range = selectedText.getRangeAt(0);
    console.log(range);
    // I've tried to use deleteContents() but without selecting the node it will not work
    range.selectNodeContents(range.commonAncestorContainer);
    range.deleteContents();
    // sometimes the text is appended outside the text input/textarea if selectNodeContents isnt used
    range.insertNode(document.createTextNode(message.translation));
});

Another doubt I have is about context menu. If I want to add some submenu to the main one, how I will handle the click event?I want to give the user the ability to select the destination language with other context menus, but not sure how to proceed. Thank you for the help.

0 Answers
Related