sta*_*ine 2 javascript google-chrome google-chrome-extension
我想做一个扩展,采取所选文本并在谷歌翻译中搜索它,但我无法弄清楚如何获取所选文本.
这是我的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"
]
}
Run Code Online (Sandbox Code Playgroud)
和我的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"]});
Run Code Online (Sandbox Code Playgroud)
和我的content_script.js文件
var sel = window.getSelection();
var selectedText = sel.toString();
chrome.extension.sendRequest({action: selectedText}, function(response) {
console.log('Start action sent');
});
Run Code Online (Sandbox Code Playgroud)
如何获取所选文本?
你使它变得比实际更复杂.您不需要在内容脚本和后台页面之间使用消息,因为contextMenus.create方法已经可以捕获所选文本.尝试将您的创作脚本调整为:
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["all"], "onclick": onRequest});
Run Code Online (Sandbox Code Playgroud)
然后调整您的函数以简单地获取info.selectionText:
function onRequest(info, tab) {
var selection = info.selectionText;
//do something with the selection
};
Run Code Online (Sandbox Code Playgroud)
请注意,如果您想远程访问Google翻译等外部网站,则可能需要调整权限设置.
| 归档时间: |
|
| 查看次数: |
5443 次 |
| 最近记录: |