Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Get selected text in a chrome extension


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.json

{
"manifest_version": 2, 
"name": "Saeed Translate",
"version": "1",
"description": "Saeed Translate for Chrome",
 "icons": {
    "16": "icon.png"
  },
"content_scripts": [ {
      "all_frames": true,
      "js": [ "content_script.js" ],
      "matches": [ "http://*/*", "https://*/*" ],
      "run_at": "document_start"
   } ],
"background": {
    "scripts": ["background.js"]
  },
"permissions": [
"contextMenus",
"background",
"tabs"
]

}

and my background.js file

var text = "http://translate.google.com/#auto/fa/";
function onRequest(request, sender, sendResponse) {
   text = "http://translate.google.com/#auto/fa/";
   text = text + request.action.toString();

 sendResponse({});
};

chrome.extension.onRequest.addListener(onRequest);
chrome.contextMenus.onClicked.addListener(function(tab) {
  chrome.tabs.create({url:text});
});
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["selection"]});

and my content_script.js file

var sel = window.getSelection();
var selectedText = sel.toString();
chrome.extension.sendRequest({action: selectedText}, function(response) {
  console.log('Start action sent');  
});

How do I get the selected text?


Solution

  • 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.