Agentleader1
Agentleader1

Reputation: 41

Chrome Extension Highlighted Text selection chrome.tabs

I'm having trouble with chrome extensions,. I have the permission "tabs" but I don't know how to retrieve the selected text on the page WITHOUT< a background page. <---- I change my mind about this, background pages I can have.

This was the scripting:

var code = document.getSelection().toString();
document.getElementsById("q").value = code;

I had placed a chrome.executeCommand method (can't remember how the method was oriented), but that didn't work either. I don't want a background page to prevent lag when this extension is installed. It may not vause much lag when I have a background, but every piece counts. Also, basically my extension will be about a Portable Google It! extension and if you highlight/select text that it will set the value of the input field automatically. Click https://www.dropbox.com/sh/c7q2puadva2vojf/GsuwWcXHjr to see the my progress so far!

Upvotes: 4

Views: 3025

Answers (1)

gkalpak
gkalpak

Reputation: 48211

(Among several possible approaches) you can achieve what you want like this:

  1. When your popup is loaded, use chrome.tabs.executeScript() to inject some code into the tab's web-page.
  2. From the injected code find and return the selected text.
  3. Populate the "search-query" input field with the returned text.
  4. when the "search" button is clicked, open a new tab with the google search results.

Below is the source code of a sample extension that does exactly that:

In maifest.json:

{
    "manifest_version": 2,

    "name":    "Test Extension",
    "version": "0.0",

    "browser_action": {
        "default_title": "Test Extension",
        "default_popup": "popup.html"
    },

    "permissions": [
        "<all_urls>"
    ],
}

In popup.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Google It!</title>
        <script type="text/javascript" src="popup.js"></script>
    </head>
    <body>
        <input type="text" id="inp" size="20" placeholder="Search query..." />
        <br />
        <input type="button" id="btn" value="Google It!" />
    </body>
</html>

In popup.js:

/* The URL for the Google search */
var google = 'http://google.com/#q=';

/* The function that finds and returns the selected text */
var funcToInject = function() {
    var range = window.getSelection().getRangeAt(0);
    var selectedText = range.cloneContents().textContent;
    return selectedText;
};
/* This line converts the above function to string
 * (and makes sure it will be called instantly) */
var jsCodeStr = ';(' + funcToInject + ')();';

window.addEventListener('DOMContentLoaded', function() {

    /* Find our input elements from `popup.html` */
    var inp = document.querySelector('input[type="text"]#inp');
    var btn = document.querySelector('input[type="button"]#btn');

    /* Open a new tab with the search results */
    btn.addEventListener('click', function() {
        var query = encodeURIComponent(inp.value);
        chrome.tabs.create({ url: google + query });
    });

    /* Inject the code into all frames of the active tab */
    chrome.tabs.executeScript({
        code: jsCodeStr,
        allFrames: true
    }, function(selectedTextPerFrame) {

        if (chrome.runtime.lastError) {
            /* Report any error */
            alert('ERROR:\n' + chrome.runtime.lastError.message);
        } else if ((selectedTextPerFrame.length > 0)
                && (typeof(selectedTextPerFrame[0]) === 'string')) {
            /* The results are as expected, 
             * populate the "search-query" input field */
            inp.value = selectedTextPerFrame[0].trim();
        }
    });
});

Upvotes: 6

Related Questions