Javascript 将参数传递到chrome.commands中
我试图做一个简单的扩展,将所选单词添加到数组中,并显示它 一切正常,但我现在正尝试添加一个键盘快捷键,以完成与右键单击>单击我的扩展图标相同的操作 我不明白如何使用chrome.commands函数将所选文本添加到数组中 这是我的背景页面中的内容:Javascript 将参数传递到chrome.commands中,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我试图做一个简单的扩展,将所选单词添加到数组中,并显示它 一切正常,但我现在正尝试添加一个键盘快捷键,以完成与右键单击>单击我的扩展图标相同的操作 我不明白如何使用chrome.commands函数将所选文本添加到数组中 这是我的背景页面中的内容: var Words = [] ... function addToArray(info, tab) { var text = info.selectionText; Words.push(text); } 还有我的chrome.co
var Words = []
...
function addToArray(info, tab) {
var text = info.selectionText;
Words.push(text);
}
还有我的chrome.commads监听器:
chrome.commands.onCommand.addListener(function(info, tab) {
addToArray(info, tab); // When I press keyboard shortcut, the word 'undefined' is added to the array...?
});
chrome.commands.onCommand.addListener(function(command) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var tab = tabs[0]; // Got the tab
// execute a content script to get the selection, for instance
// You will need the "activeTab" permission
chrome.tabs.executeScript(
tab.id,
{code: "getSelection().toString();"},
function(results){
Words.push(results[0]);
}
);
});
});
当我按下快捷键时,出现了一些问题,因为我在数组中得到了“未定义”,但我不知道是什么!后台页面上的控制台中没有错误
有人能帮我解决这个问题吗?谢谢
显然,chrome.commands监听器正在工作,因为我没有定义,但是,如果我将
警报('test')
放入其中,警报确实会显示出来。简而言之,您不能。
如中所述,onCommand的回调仅获取触发的命令的名称
因此,要获得选择,您需要自己从侦听器中查询:
chrome.commands.onCommand.addListener(function(info, tab) {
addToArray(info, tab); // When I press keyboard shortcut, the word 'undefined' is added to the array...?
});
chrome.commands.onCommand.addListener(function(command) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var tab = tabs[0]; // Got the tab
// execute a content script to get the selection, for instance
// You will need the "activeTab" permission
chrome.tabs.executeScript(
tab.id,
{code: "getSelection().toString();"},
function(results){
Words.push(results[0]);
}
);
});
});