Skip to content Skip to sidebar Skip to footer

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 selecte

Solution 1:

After researching on and off for the last 24 hours I finally have a working solution. Because I'm accessing a DOM Element, I needed to inject a content script and pass information back and forth from the background script. I also added the activeTab permission to my manifest.

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

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

functionsendServiceRequest(selectedText) {                                         
    var serviceCall = 'http://www.google.com/search?q=' + selectedText;
    chrome.tabs.create({url: serviceCall});
}

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

about sending messages among bg.html, popup.html and contentscript.js

Post a Comment for "Window.getselection Returning Undefined Or Null"