2011-05-02 71 views
0

我有一個名爲file.js的內容創建變量「found」。我想將varibale「found」的值發送到popup.html中的文本框中。在file.js中(我知道varible found正在工作,使用警報進行測試)。Chrome擴展消息傳遞 - 包含的代碼

chrome.extension.sendRequest({foundlinks: found}, function(response) { 
console.log(response); 
}); 

在Popup.html:

function pulllinks(){ 

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 

    document.getElementById("box").value = request.foundlinks; 

    sendResponse({}); 
}); 

而且在popup.html的形式:

<input type = "button" onclick="pulllinks();" name = "box" id="box" value = "Grab Links From Page" /> 

然而,它沒有做任何事情。有任何想法嗎?

謝謝!

回答

1

你必須發送相反的方向請求 - 內容腳本從彈出:

popup.html:

function pulllinks(){ 
    chrome.tabs.getSelected(null, function(tab) { 
     chrome.tabs.sendRequest(tab.id, {cmd: "findLinks"}, function(response) { 
      document.getElementById("box").value = response.foundlinks; 
     }); 
    }); 

} 

file.js:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    if(request.cmd == "findLinks") { 
     //calculate "found" value and send it back 
     sendResponse({foundlinks: found}); 

    } 
}); 
+0

哇,像一個魅力工作。感謝您的解釋。 – NoviceCoding 2011-05-02 16:55:09

1

首先,您的聽衆onRequest應該從一開始就存在,因此請將其移到pulllinks函數之外。其次,你如何確保在彈出窗口打開時你的sendRequest被觸發?

+0

好的,將函數pulllinks移到頂端並刪除函數並保留代碼。不知道第二部分你的意思。 – NoviceCoding 2011-05-02 16:45:02

+0

我的意思是,對於「第二部分」,您如何確保您的內容腳本正在發送請求*而您的彈出窗口已打開? – mattsven 2011-05-02 16:48:01

+0

事情是我不知道這些請求如何工作,所以我假設通過運行該功能時,按鈕被點擊它會啓動消息。 – NoviceCoding 2011-05-02 16:49:57