Google chrome Chrome扩展:如何捕获选定文本并发送到web服务
对于GoogleChrome扩展,我需要捕获网页中的选定文本并发送到web服务。我卡住了 首先我尝试了一个bookmarklet,但Mac上的Chrome似乎有一些bookmarklet错误,所以我决定写一个扩展 我在ext中使用此代码:Google chrome Chrome扩展:如何捕获选定文本并发送到web服务,google-chrome,google-chrome-extension,Google Chrome,Google Chrome Extension,对于GoogleChrome扩展,我需要捕获网页中的选定文本并发送到web服务。我卡住了 首先我尝试了一个bookmarklet,但Mac上的Chrome似乎有一些bookmarklet错误,所以我决定写一个扩展 我在ext中使用此代码: function getSelText(){ var txt = 'nothing'; if (window.getSelection){ txt = "1" + window.getSelection(); } els
function getSelText(){
var txt = 'nothing';
if (window.getSelection){
txt = "1" + window.getSelection();
} else if (document.getSelection) {
txt = "2" + document.getSelection();
} else if (document.selection) {
txt = "3" + document.selection.createRange().text;
} else txt = "wtf";
return txt;
}
var selection = getSelText();
alert("selection = " + selection);
当我点击我的扩展图标时,我得到一个“1”。因此,我认为在浏览器窗口外选择的行为会导致浏览器不再将文本视为“已选择”
只是一个理论
想法?您的代码不清楚它在哪里。我的意思是,如果这段代码是弹出式html或背景html,那么您看到的结果是正确的,这些窗口中的任何内容都不会被选中 您需要将此代码放置在内容脚本中,以便它能够访问页面的DOM,然后当您单击浏览器操作时,您需要向内容脚本发送消息以获取当前文档选择。您可以使用。基本上,您的“背景页面”将向您的服务发送请求。例如,假设您有一个“弹出窗口”,一旦您单击它,它将执行“谷歌搜索”,这是您的服务 content_script.js 在您的内容脚本中,我们需要侦听来自您的扩展的请求,以便将所选文本发送给它:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
background.html
现在在后台页面中,您可以处理弹出窗口,以便我们知道我们单击了弹出窗口。一旦我们点击了它,回调就会启动,然后我们可以使用“消息传递”来获取所选文本,从而访问内容脚本
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function(response){
sendServiceRequest(response.data);
});
});
function sendServiceRequest(selectedText) {
var serviceCall = 'http://www.google.com/search?q=' + selectedText;
chrome.tabs.create({url: serviceCall});
}
如您所见,我在内容脚本中注册了一个侦听器,以允许我的扩展从中发送和接收消息。一旦我收到一条信息,我就通过搜索谷歌来处理它
希望您可以使用我上面解释的内容,并将其应用到您的场景中。我只需要警告您,上面编写的代码没有经过测试,因此它们可能是拼写或语法错误。但是,通过查看您的检查器可以很容易地找到它们:)内容脚本
document.addEventListener('mouseup',function(event)
{
var sel = window.getSelection().toString();
if(sel.length)
chrome.extension.sendRequest({'message':'setText','data': sel},function(response){})
})
背景页面
<script>
var seltext = null;
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
{
switch(request.message)
{
case 'setText':
window.seltext = request.data
break;
default:
sendResponse({data: 'Invalid arguments'});
break;
}
});
function savetext(info,tab)
{
var jax = new XMLHttpRequest();
jax.open("POST","http://localhost/text/");
jax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
jax.send("text="+seltext);
jax.onreadystatechange = function() { if(jax.readyState==4) { alert(jax.responseText); }}
}
var contexts = ["selection"];
for (var i = 0; i < contexts.length; i++)
{
var context = contexts[i];
chrome.contextMenus.create({"title": "Send to Server", "contexts":[context], "onclick": savetext});
}
</script>
var seltext=null;
chrome.extension.onRequest.addListener(函数(请求、发送方、发送响应)
{
开关(请求消息)
{
案例“setText”:
window.seltext=request.data
打破
违约:
sendResponse({data:'无效参数'});
打破
}
});
函数savetext(信息,选项卡)
{
var jax=newXMLHttpRequest();
open(“POST”http://localhost/text/");
setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
send(“text=“+seltext”);
jax.onreadystatechange=function(){if(jax.readyState==4){alert(jax.responseText);}
}
变量上下文=[“选择”];
for(var i=0;i
manifest.json
{
"name": "Word Reminder",
"version": "1.0",
"description": "Word Reminder.",
"browser_action": {
"default_icon": "images/stick-man1.gif",
"popup":"popup.html"
},
"background_page": "background.html",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["js/myscript.js"]
}
],
"permissions": [
"http://*/*",
"https://*/*",
"contextMenus",
"tabs"
]
}
{
“姓名”:“文字提醒”,
“版本”:“1.0”,
“说明”:“文字提示”,
“浏览器操作”:{
“默认图标”:“images/stick-man1.gif”,
“popup”:“popup.html”
},
“背景页面”:“background.html”,
“内容脚本”:[
{
“匹配项”:[“
享受使用内容脚本并不是一个很好的解决方案,因为它会注入到所有文档中,包括iframe广告等。我从其他页面中得到一个空文本选择,而不是我在混乱的网站上预期的一半
更好的解决方案是只向所选选项卡中插入代码,因为这是所选文本的所在位置。jquery doc ready部分的示例:
$(document).ready(function() {
// set up an event listener that triggers when chrome.extension.sendRequest is fired.
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
// text selection is stored in request.selection
$('#text').val( request.selection );
});
// inject javascript into DOM of selected window and tab.
// injected code send a message (with selected text) back to the plugin using chrome.extension.sendRequest
chrome.tabs.executeScript(null, {code: "chrome.extension.sendRequest({selection: window.getSelection().toString() });"});
});
像这样简单的东西不需要谷歌API
我将以Bing在线服务为例。请注意,URL设置为接受一个参数:
var WebService='http://www.bing.com/translator/?text=';
frameID.contentWindow.document.body.addEventListener('contextmenu',function(e){
T=frameID.contentWindow.getSelection().toString();
if(T!==''){e.preventDefault(); Open_New_Tab(WebService+encodeURIComponent(T)); return false;}
},false);
注意:上面使用的函数“Open_New_Tab()”是一个虚构的函数,它接受带有编码的选定文本的webservice URL作为参数
基本上就是这样。不需要使用这种代码。Chrome扩展只在Chrome中运行,所以只需优化它,使其在Chrome上运行,而无需复杂的跨浏览器操作。您必须执行window.getSelection().toString()获取所选文本。Chrome extensions可以定义一个contextmenu选项,该选项仅在选择某些文本时显示。API提供了一个返回所选文本的属性:请参阅文档和/或。是的。需要更清楚地了解哪些文件包含哪些内容。您能编辑答案并输入文件名吗?我在段落哪一个是内容脚本,哪一个是背景页面。我添加了两个标题以使其更清晰。我可以看看manifest.json吗?我正在尝试学习开发chrome扩展。什么是内容脚本,什么是background.html?内容是网站,bakcground是扩展html文件?而不是我们使用的回调可以使用window.onload
并包装其中的所有函数。