Chrome扩展程序:如何捕获所选文本并发送到网络服务

phi*_*son 34 google-chrome google-chrome-extension

对于Google Chrome扩展程序,我需要捕获网页中的选定文本并发送到网络服务.我被卡住了!

首先我尝试了一个书签,但Mac上的Chrome似乎有一些书签错误,所以我决定写一个扩展名.

我在我的分机中使用此代码:

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);
Run Code Online (Sandbox Code Playgroud)

当我点击我的扩展图标时,我得到一个"1".所以我认为在浏览器窗口之外选择的行为导致浏览器不再将文本视为"已选择".

只是一个理论....

想法?

Moh*_*our 43

您可以使用Extensions Messaging执行此操作.基本上,您的"后台页面"会将请求发送给您的服务.例如,假设您有一个"弹出窗口",一旦您点击它,它将执行"Google搜索",这是您的服务.

content_script.js

在您的内容脚本中,我们需要侦听来自您的扩展程序的请求,以便我们向其发送所选文本:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection")
      sendResponse({data: window.getSelection().toString()});
    else
      sendResponse({}); // snub them.
});
Run Code Online (Sandbox Code Playgroud)

background.html

现在在后台页面中,您可以处理弹出的onclick事件,以便我们知道我们点击了弹出窗口.一旦我们点击它,回调就会触发,然后我们可以使用"Messaging"向内容脚本发送请求以获取所选文本.

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});
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我在内容脚本中注册了一个侦听器,以允许我的扩展程序从其发送和接收消息.然后,当我收到消息后,我会通过搜索Google来处理它.

希望您可以使用我上面解释的内容并将其应用到您的场景中.我只需要警告你,上面编写的代码没有经过测试,因此它们可能是拼写错误或语法错误.但是通过查看你的Inspector可以轻松找到这些:)

  • 我可以看看manifest.json我正在努力学习开发chrome扩展. (4认同)
  • 我在段落中解释了哪一个是内容脚本,哪一个是后台页面.我添加了两个标题以使其更清晰. (2认同)

Jay*_*ran 6

内容脚本

document.addEventListener('mouseup',function(event)
{
    var sel = window.getSelection().toString();

    if(sel.length)
        chrome.extension.sendRequest({'message':'setText','data': sel},function(response){})
})
Run Code Online (Sandbox Code Playgroud)

背景页面

<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>
Run Code Online (Sandbox Code Playgroud)

的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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是我在一个扩展程序中下载所有内容的链接.看完之后,我尝试了自己并发表了.

这是完整的来源

http://vikku.info/programming/chrome-extension/get-selected-text-send-to-web-server-in-chrome-extension-communicate-between-content-script-and-background-page.htm

请享用