chorme 扩展 - 如何替换用户选择的文本

问题描述

我正在研究翻译 Chrome 扩展程序。我想在用户单击上下文菜单语音后获取用户选择并进行翻译。我已经实现了这段代码,但没有按预期工作。我已经在 instagram 上对其进行了测试,似乎可以在 DM 输入字段中使用。对于消息或状态文本区域的 facebook 文本输入,相同的代码将无法按预期工作。翻译后如何管理所选文本的替换?

背景.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));
});

我的另一个疑问是关于上下文菜单。如果我想向主菜单添加一些子菜单,我将如何处理点击事件?我想让用户能够使用其他上下文菜单选择目标语言,但不确定如何继续。 谢谢你的帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)