我想制作一个扩展程序来获取选定的文本并在谷歌翻译中搜索它,但我不知道如何获取选定的文本。
这是我的 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');
});
如何获取选定的文本?