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

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


首先,我尝试了一个书签,但是Mac上的Chrome似乎存在一些书签问题,因此我决定编写一个扩展程序。


我在ext中使用以下代码:


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”。因此,我认为在浏览器窗口之外进行选择的行为导致浏览器不再将文本视为“已选择”。


只是理论而已...


有什么想法吗?


子衿沉夜
浏览 778回答 3
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() });"});});
打开App,查看更多内容
随时随地看视频慕课网APP