2

我想制作一个扩展程序来获取选定的文本并在谷歌翻译中搜索它,但我不知道如何获取选定的文本。

这是我的 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"
]

}

和我的 background.js 文件

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"]});

和我的 content_script.js 文件

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

如何获取选定的文本?

4

1 回答 1

10

你让它变得比实际上更复杂一些。您不需要在内容脚本和背景页面之间使用消息,因为 contextMenus.create 方法已经可以捕获选定的文本。尝试将您的创作脚本调整为:

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

然后调整您的函数以简单地获取 info.selectionText:

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

请注意,如果您想远程访问像谷歌翻译这样的外部网站,您可能需要调整您的权限设置。

于 2013-01-11T03:45:49.460 回答