Jonathan Ross Flavell
Jonathan Ross Flavell

Reputation: 37

Capture selected text using keyboard shortcut

I created a Chrome extension which adds a context menu item to search 4 stores for the selected text on a page. In this sense the extension works fine, however I was asked by a user to implement a keyboard short cut also. So far I have a short cut working, but am having no luck in capturing to selected text in order to do the search. Anyone able to help out here?

Manifest.json

{
    "name": "Context Shop Search",
    "description": "Searches shops for selected text using the context menu",
    "version": "0.6",
    "manifest_version": 2,
    "permissions": ["contextMenus", "tabs"],
    "background": {
        "scripts": ["jquery.js", "background.js"]
    },
    "commands": {
        "search": {
            "suggested_key": {
                "default": "Ctrl+Shift+S"
            },
            "description": "Search Stores"
        }
    } 
}

Background.js

var urls = ["http://groceries.asda.com/asda-webstore/landing/home.shtml?cmpid=ahc-_-ghs-asdacom-dsk-_-hp-_-sub_title#/search/", "http://www.waitrose.com/shop/HeaderSearchCmd?defaultSearch=GR&searchTerm=&search=Search", "http://www.ocado.com/webshop/getSearchProducts.do?clearTabs=yes&isFreshSearch=true&entry=", "http://www.tesco.com/groceries/Product/Search/Default.aspx?searchBox=&newSort=true&search.x=-1042&search.y=-63&search=Search"];

var searchUrls = [];

function Search(info) {
    //alert(info.selectionText);

    var selection = info.selectionText;
    searchUrls[0] = urls[0].concat(selection);
    searchUrls[1] = urls[1].replace("searchTerm=", "searchTerm=".concat(selection));
    searchUrls[2] = urls[2].concat(selection);
    searchUrls[3] = urls[3].replace("searchBox=", "searchBox=".concat(selection));

    chrome.windows.create({
        url: searchUrls,
        height: 768,
        width: 1024
    });

}

chrome.commands.onCommand.addListener(function (command) {
    alert("sometext");
});

chrome.contextMenus.create({
    id: "ctxtSearch",
    title: "Search '%s' in all stores",
    contexts: ["selection"],
    onclick: Search
}) 

Have been searching around numerous sites and found many variations of the answer 'use a content script', but most of the examples were using various browser actions or click events which, obviously, I don't want to use, and being fairly new to javascript (this is the first thing I've written with it) found it difficult to try and tweak these examples to suit my needs.

Any input greatly appreciated, Thanks.

Upvotes: 0

Views: 696

Answers (1)

rsanchez
rsanchez

Reputation: 14657

Yes, you'll need to run code in the current tab to get the selection, but it's nothing hard in this case:

chrome.commands.onCommand.addListener(function(command) {
  if(command === "search") {
    chrome.tabs.executeScript( {
      code: "window.getSelection().toString();"
    }, function(selection) {
      Search({selectionText: selection[0]});
    });
  }
});

chrome.tabs.executeScript without specifying a tabId parameter will execute code in the context of the active tab of the current window, and will call your callback function with the last expression evaluated in that code (actually the callback function receives an array of values because you could make executeScript to run code in more than one tab).

On a side note, it is common practice in javascript to use lowercase for the first letter of function names, so you may want to rename Search to search.

Upvotes: 3

Related Questions