2

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(). No matter what I do, the console and alerts display blank. Could anyone explain why?

I'm doing this in a local Chrome extension.

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

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.

Brian
  • 4,274
  • 2
  • 27
  • 55
  • you can do this `window.getSelection().toString()` to save some space, it works fine for me. You know when you click something it may cancel your selection. So when a selection is cancelled, the getselection should return empty string – Theofilos Mouratidis Jan 26 '14 at 04:53
  • After posting, I did some more searching and came across some similar questions which said DOM Elements can only be accessed by injecting a `content.js` script to run on the page you want access to. [This one was helpful](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script),so I'll try that and add an update. – Brian Jan 26 '14 at 04:55
  • @ΘεόφιλοςΜουρατίδης I tried that method as well, and it didn't print in the console or an alert (just for the sake of trying). I also tried using `onmousedown`, but I couldn't get that to work either. I'm working specifically in Chrome...would you verify again for me? – Brian Jan 26 '14 at 04:57
  • See this answer: http://stackoverflow.com/a/19100054/1507998 – rsanchez Jan 26 '14 at 12:00

1 Answers1

6

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

function sendServiceRequest(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

Community
  • 1
  • 1
Brian
  • 4,274
  • 2
  • 27
  • 55
  • Does it work on Disqus comments? I'm getting failure of `getSelection()` there with Chrome, normal with Firefox. – Lori Nov 08 '15 at 01:20
  • I haven't tested with Firefox as it was meant as a Chrome extension. – Brian Aug 26 '17 at 18:18