【问题标题】:Chrome Extension: how to capture selected text and send to a web serviceChrome 扩展程序:如何捕获选定的文本并发送到 Web 服务
【发布时间】:2011-02-07 06:49:49
【问题描述】:

对于 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);

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

只是一个理论......

想法?

【问题讨论】:

  • 不需要使用那种代码。 Chrome 扩展程序只能在 Chrome 中运行,因此只需对其进行优化以在 Chrome 上运行,而不需要复杂的跨浏览器内容。您必须执行 window.getSelection().toString() 才能获取选定的文本。
  • Chrome 扩展程序可以定义一个上下文菜单选项,该选项仅在选择某些文本时显示。 API 提供了一个返回所选文本的属性:请参阅 chrome.contextMenus 文档和/或 this answer

标签: google-chrome google-chrome-extension


【解决方案1】:

你不需要谷歌 API 来做这么简单的事情......

我将以必应在线服务为例。请注意,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()”是一个虚构的函数,它接受带有编码的选定文本作为参数的 Web 服务 URL。

基本上就是这样。

【讨论】:

    【解决方案2】:

    您可以使用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.
    });
    

    background.html

    现在在后台页面中,您可以处理弹出窗口onclick event,以便我们知道我们点击了弹出窗口。一旦我们点击它,回调就会触发,然后我们可以使用“消息传递”send a request 到内容脚本来获取选定的文本。

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

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

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

    【讨论】:

    • 是的。需要更清楚地了解哪些文件包含哪些内容。您能否编辑答案并输入文件名?
    • 我在段落中解释了哪一个是内容脚本,哪一个是背景页面。我现在添加了两个标题以使其更清晰。
    • 我可以看看 manifest.json 我正在尝试学习开发 chrome 扩展。
    • 什么是content_script,什么是background.html? content 是网站,bakcground 是扩展 html 文件?
    • 我们可以使用window.onload 代替回调并将所有函数包装在其中。
    【解决方案3】:

    使用 content_scripts 并不是一个很好的解决方案,因为它会注入到所有文档中,包括 iframe-ads 等。我从其他页面中得到一个空的文本选择,而不是我在混乱的网站上预期的一半时间。

    更好的解决方案是仅将代码注入选定的选项卡,因为无论如何这是您选择的文本所在的位置。 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() });"});
    });
    

    【讨论】:

      【解决方案4】:

      内容脚本

      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>
      

      ma​​nifest.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"
        ]
      }
      

      这是我在一个扩展程序中下载的链接。 读完这篇文章后,我自己尝试并发表了。

      这是完整的源代码

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

      享受

      【讨论】:

        【解决方案5】:

        从您的代码中不清楚它在哪里。我的意思是,如果此代码在弹出 html 或背景 html 中,那么您看到的结果是正确的,这些窗口中的任何内容都不会被选中。

        您需要将此代码放在内容脚本中,以便它可以访问页面的 DOM,然后当您单击浏览器操作时,您需要向内容脚本发送消息以获取当前文件选择。

        【讨论】:

          猜你喜欢
          • 2018-08-21
          • 2021-10-03
          • 1970-01-01
          • 2016-03-14
          • 1970-01-01
          • 2013-10-10
          • 1970-01-01
          • 2015-08-16
          • 1970-01-01
          相关资源
          最近更新 更多