Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...