为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

子衿沉夜 2019-11-26 14:39:15
对于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”。因此,我认为在浏览器窗口之外进行选择的行为导致浏览器不再将文本视为“已选择”。只是理论而已...有什么想法吗?
查看完整描述

3 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

使用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() });"});

});


查看完整回答
反对 回复 2019-11-26
  • 3 回答
  • 0 关注
  • 774 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信