Get selected text in a chrome extension

后端 未结 1 1904
南笙
南笙 2020-12-16 08:39

I wanna make an extension that takes the selected text and searches it in google translate but I can\'t figure out how to get the selected text.

Here is my manifest.

相关标签:
1条回答
  • 2020-12-16 09:04

    You are making it a bit more complicated than it really is. You don't need to use a message between the content script and background page because the contextMenus.create method already can capture selected text. Try adjusting your creations script to something like:

    chrome.contextMenus.create({title:"Translate '%s'",contexts: ["all"], "onclick": onRequest});
    

    Then adjust your function to simply get the info.selectionText:

    function onRequest(info, tab) {
    var selection = info.selectionText;
    //do something with the selection
    };
    

    Please note if you want to remotely access an external site like google translate you may need to adjust your permissions settings.

    0 讨论(0)
提交回复
热议问题