window.getSelection返回undefined或null

Bri*_*ian 2 javascript google-chrome google-chrome-extension

这可能是一个非常初学的问题,但是我要拔掉头发,因为我无法弄清楚我做错了什么.此时,我要做的就是让所选文本在警报或控制台中打印(用于测试).我确保已将.toString()方法添加到返回的对象中,window.getSelection().无论我做什么,控制台和警报显示为空白.谁有人解释为什么?

我在本地Chrome扩展程序中执行此操作.

的manifest.json

{
    "manifest_version": 2,
    "name":"Testing",
    "version": "0.1",
    "icons": {
       "48":"48.png"
    },

    "background": {
        "scripts": [ "background.js" ]
    },

    "permissions":[ "tabs" ],

    "browser_action": {
        "default_icon": { "19":"img19.png" }
    }
}
Run Code Online (Sandbox Code Playgroud)

JavaScript的

chrome.browserAction.onClicked.addListener(function(tab) {
    var selObj = window.getSelection();
    var selectionText = selObj.toString();
    alert(selectionText);       // displays a blank alert
    console.log(selectionText); // adds a blank line in the console
});
Run Code Online (Sandbox Code Playgroud)

我在学.提前致谢.

Bri*_*ian 6

在研究过去24小时后,我终于有了一个有效的解决方案.因为我正在访问DOM元素,所以我需要注入内容脚本并在后台脚本中来回传递信息.我还activeTab向我的清单添加了权限.

的manifest.json

{
    "manifest_version": 2,
    "name":"Simple Highlighter",
    "version": "1.0",
    "icons": {
        "19":"img19.png",
        "48":"48.png"
    },

    "content_scripts": [{                   
            // "matches": ["<all_urls>"],   only used for testing
            "js":["contentscript.js"]
        }],

     "background": {
        "scripts": [ "background.js" ]
    },

    "permissions":[ "tabs", "activeTab" ],

    "description": "Highlight web text and send it to a new Google Doc",

    "browser_action": {
        "default_icon": { "19":"img19.png" },
        "default_title":"Simple Highlighter"
    }
}
Run Code Online (Sandbox Code Playgroud)

background.js

chrome.browserAction.onClicked.addListener(function() {                                                 
    chrome.tabs.query({active: true, windowId: chrome.windows.WINDOW_ID_CURRENT}, function(tabs) {      
        chrome.tabs.sendMessage(tabs[0].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)

contentscript.js

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

显然,这不是我最初要做的事情......但是.但是,我有它传递数据,所以我接下来将致力于突出显示功能.

参考链接

Chrome扩展程序获取所选文字

关于在bg.html,popup.html和contentscript.js之间发送消息