简体   繁体   English

window.getSelection返回未定义或null

[英]window.getSelection returning undefined or null

This is probably a very beginner question, but I'm about to pull my hair out because I can't figure out what I'm doing wrong. 这可能是一个非常初学者的问题,但是我要拔掉头发,因为我无法弄清楚自己在做什么错。 At this point, all I'm trying to do is get the selected text to print in an alert or the console (for testing). 此时,我要做的就是将选定的文本打印在警报或控制台中(用于测试)。 I've made sure .toString() method has been added to the returned Object from window.getSelection(). 我确定.toString()方法已添加到window.getSelection().返回的对象中window.getSelection(). No matter what I do, the console and alerts display blank. 不管我做什么,控制台和警报都显示为空白。 Could anyone explain why? 谁能解释为什么?

I'm doing this in a local Chrome extension. 我正在本地Chrome扩展程序中执行此操作。

manifest.json 的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" }
    }
}

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

I'm learning. 我在学。 Thanks in advance. 提前致谢。

After researching on and off for the last 24 hours I finally have a working solution. 经过最近24小时的反复研究之后,我终于有了一个可行的解决方案。 Because I'm accessing a DOM Element, I needed to inject a content script and pass information back and forth from the background script. 因为我正在访问DOM元素,所以需要注入内容脚本并从后台脚本来回传递信息。 I also added the activeTab permission to my manifest. 我还向清单中添加了activeTab权限。

manifest.json 的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"
    }
}

background.js 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});
}

contentscript.js contentscript.js

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

Obviously, this isn't doing what I originally set out to do...yet. 显然,这并没有实现我最初打算做的事情。 But, I have it passing data, so I'll be working on the highlighting functionality next. 但是,我有它传递数据,因此接下来我将研究突出显示功能。

Reference Links 参考链接

Chrome Extension get selected text Chrome扩展程序获取所选文本

about sending messages among bg.html, popup.html and contentscript.js 关于在bg.html,popup.html和contentscript.js之间发送消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM