2014-09-19 193 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]); 
     } 
    ); 
    }); 
});