2014-09-19 195 views
0

我正在尝试做一个简单的扩展,将选定的单词添加到数组中并显示它。将参数传递给chrome.commands

一切正常,但我现在试图添加一个键盘快捷方式来执行相同的操作,如右击>单击我的扩展名图标。

我不明白如何使用chrome.commands函数将选定的文本添加到数组。

这是我在我的背景页:

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侦听器正在工作,因为我得到了未定义的,但是,如果我把alert('test')放入它中,警报也会显示出来。

回答

1

总之,你不能。

the documentation所述,onCommand的回调只会获得触发命令的名称。

因此,要获得一个选择,你需要自己从听者莫名其妙地查询它:

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]); 
     } 
    ); 
    }); 
});