侦听器已添加到您的背景页面中,因此window.getSelection() 指的是在您(自动生成的)背景页面中选择的文本,而不是在活动选项卡中。
为了从活动选项卡中检索选定的文本,您需要注入一些代码来为您完成并报告结果。
例如:
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"
}
}
}
还有一点需要注意:
根据 this answer(以及我自己使用 Chrome v31 的经验),关于声明键盘快捷键(又名命令)的官方文档是错误地罢工> 声明您可以以编程方式设置组合键。
事实(如上述答案中的“被盗”)是:
在 Chrome 29(及更高版本)上,您必须导航到 chrome://extensions/ 并向下滚动到页面底部。右侧有一个按钮Keyboard shortcuts。
弹出模式对话框,其中包含在清单文件中注册了某些命令的所有扩展。但是快捷方式本身是Not set,所以用户必须手动设置它们。
(强调我的)
更新:
真相是这样的:
如果suggested_key未已在用户平台上用作keyboard shortcut,则绑定按预期工作。
如果suggested_key 已绑定到不同的命令,则未设置绑定。用户必须导航到chrome://extensions/ 并单击页面底部的Keyboard shortcuts 按钮。在弹出的对话框中,用户必须手动为注册的命令分配快捷方式。
测试时,修改manifest中的suggested_key后,需要卸载并重新安装扩展才能使修改生效。简单地重新加载或禁用并重新启用扩展是行不通的。 (感谢rsanchez,感谢您的收获。)