2012-07-23 81 views
3

之間的功能在谷歌Chrome擴展我想一個內容腳本和彈出頁面之間傳遞消息。當內容腳本的信號被彈出頁面發送到內容腳本時,我也希望內容腳本中的函數被觸發。谷歌瀏覽器擴展 - 信息+來電彈出頁面和內容腳本

的消息在谷歌Chrome瀏覽器擴展開發者文檔中的部分,指出消息可以通過「從您的內容腳本擴展頁面,反之亦然」(從http://code.google.com/chrome/extensions/messaging.html報價)

這是否意味着我可以在內容腳本和彈出頁面之間發送/接收消息?因爲我看到的用法是用於後臺頁面和內容腳本之間的通信。

還是我必須建立一個3 - 通過route--即單向消息。 內容腳本< - >背景頁< - >彈出頁面。如果是這種情況,我如何在背景頁面< - >彈出頁面之間建立消息傳遞?

以及如何在火災內容腳本的功能,從彈出頁面發送信號到內容腳本後?這是否也需要後臺腳本存在?

回答

8

內容腳本只能將消息發送給後臺頁面。如果你想從內容腳本將消息發送到一個彈出,你必須:

  1. 從內容腳本將消息發送到後臺頁面。

    chrome.runtime.sendMessage(...message... , function() { /*response*/ }); 
    
  2. 在後臺接收郵件。

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { ... }); 
    
  3. 將消息傳遞給彈出窗口。要獲取對彈出窗口的全局window對象的引用,請使用chrome.extension.getViews。注:與其他大多數鉻的API,這種方法是同步的:

    var popupWindows = chrome.extension.getViews({type:'popup'}); 
    if (popupWindows.length) { // A popup has been found 
        // details is the object from the onMessage event (see 2) 
        popupWindows[0].whatever(message, sendResponse); 
    } 
    
  4. 在彈出窗口中,定義whatever方法。

    function whatever(message, sendResponse) { 
        // Do something, for example, sending the message back 
        sendResponse(message); 
    } 
    
  5. sendResponse(4)被調用,details.sendResponse(參見圖3)被調用。這反過來,調用function() { /*response*/ }從1

注:chrome.runtime.sendMessage/onMessage在Chrome只支持26+。如果您還想支持舊版瀏覽器,請使用chrome.extension.sendMessage

+0

2個doubts--我可以使用長壽命的連接,從內容腳本將消息發送到後臺頁面?其次,如何根據彈出窗口中的某些用戶操作調用內容腳本中的某個功能?非常感謝... – Arvind 2012-07-23 17:56:48

+1

@ Arvind是的。 1:['chrome.extension.connect'](http://code.google.com/chrome/extensions/extension.html#method-connect)和2:['chrome.tabs.executeScript'](http:/ /code.google.com/chrome/extensions/tabs.html#method-executeScript)(以插入代碼)和/或['chrome.tabs.query'](http://code.google.com/chrome/extensions /tabs.html#method-query)(獲取tabId)+ ['chrome.tabs.sendMessage'](http://code.google.com/chrome/extensions/tabs.html#method-sendMessage) – 2012-07-23 18:01:10