The listener is added in your background page, so window.getSelection()
refers to the text selected in your (automatically generated) background page, not in the active tab.
In order to retrieve the selected text from the active tab, you need to inject a little code to do it for you and report back with the result.
E.g.:
background.js:
/* The function that finds and returns the selected text */
var funcToInject = function() {
var selection = window.getSelection();
return (selection.rangeCount > 0) ? selection.toString() : '';
};
/* This line converts the above function to string
* (and makes sure it will be called instantly) */
var jsCodeStr = ';(' + funcToInject + ')();';
chrome.commands.onCommand.addListener(function(cmd) {
if (cmd === 'selectedText') {
/* Inject the code into all frames of the active tab */
chrome.tabs.executeScript({
code: jsCodeStr,
allFrames: true // <-- inject into all frames, as the selection
// might be in an iframe, not the main page
}, 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 */
alert('Selected text: ' + selectedTextPerFrame[0]);
}
});
}
});
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"permissions": ["<all_urls>"],
"commands": {
"selectedText": {
"description": "Retrieve the selected text in the active tab"
}
}
}
One more thing to note:
Accroding to this answer (and my own experience with Chrome v31) the official docs on declaring a keyboard shortcut (a.k.a. command) are falsely stating you can set the key-combination programmatically.
The truth (as "stolen" from the aforementioned answer) is:
On Chrome 29 (and later) you have to navigate to chrome://extensions/
and scroll down to the bottom of the page. On the right side there is a button Keyboard shortcuts
.
Modal dialog pops up with all extensions that have registered some commands in their manifest file. But the shortcuts itself are Not set
so the user must set them manually.
(emphasis mine)
UPDATE:
The whole truth is this:
If the suggested_key
is not already in use as a keyboard shortcut on the user's platform, then the binding works as expected.
If the suggested_key
is already bound to a different command, then the binding is not set up. The user has to navigate to chrome://extensions/
and click the Keyboard shortcuts
button at the bottom of the page. In the dialog that pops up, the user has to assign a shortcut to the registered command manually.
While testing, after changing the suggested_key
in manifest, you need to uninstall and re-install the extension for the changes to take effect. Simply reloading or disabling and re-enabling the extension won't work. (Thx to rsanchez for this nice catch.)