2013-02-27 72 views
0

我的理解是沒有辦法直接頁面操作和教改嘗試腳本之間的溝通,所以我這樣做:PageAction,背景頁面,並ContentScript之間的通信一款Chrome擴展程序

page_action.html

chrome.extension.sendRequest(
    {to:"background",key:"color",val:"red"}, 
    function(response) { 
     console.log(response) ; 
    } 
) ; 

background.js

chrome.extension.onRequest.addListener(
    function(request,sender,sendResponse) { 
     if (request.to == "background") { 
      console.log("Request recieved to Background") ; 
      request.to = "content" ; 
      chrome.extension.sendRequest(request,function(response) { 
       sendResponse(response) ; 
      }) ; 
     } 
    } 
) ; 

我ñcontent.js

(function(){ 
    // ... 
    // Do something initial 
    // ... 
    // Now start to listen 
    chrome.extension.onRequest.addListener(
     function(request,sender,sendResponse) { 
      if (request.to == "content") { 
       // Do something with request.key and request.val 
       console.log("Request recieved to Content Script") ; 
       sendResponse({status:'from content'}) ; 
      } 
     } 
    ) ; 
}()) ; 

頁面操作和背景之間的通訊作品完美,但背景和內容腳本之間沒有發生。我在這裏錯過了什麼?如何正確溝通對方?最重要的是,還有另一種讓頁面操作更直接的通信到內容腳本的方式嗎?

回答

4

幸運的是,有一種方法可以直接在Page ActionContent Script之間進行通信,這將通過tabs.sendMessage方法進行。

您可以從chrome.pageAction.onClicked或簡單的chrome.tabs.query獲得id

一旦你有標籤的ID,你想從你的Page Action將消息發送到,只是發送消息是這樣的:

page_action.html

chrome.tabs.query({active:true,currentWindow:true},function(tabs){ 
    chrome.tabs.sendMessage(tabs[0].id,{message:"text"}, function(response){ 
    //If you need a response, do stuff with it here 
    }); 
}); 

content.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ 
    //Do stuff here 
    //sendResponse({message:"stuff"}); 
}); 

在旁註中,sendRequestonRequest已被其Message對應部分取代。

+0

謝謝!奇蹟般有效!只是沒有「tabId」,只有「ID」:) – Digerkam 2013-02-28 05:07:00

+0

@Digerkam這就是我從內存中輸入它。感謝您指出了這一點。 – BeardFist 2013-02-28 05:22:43

+0

我的榮幸。我可以請你看看這個問題,如果你嘗試類似的東西:http://stackoverflow.com/questions/15102282/how-to-execute-scripts-on-background-page-of-a-chrome-擴展再次謝謝! – Digerkam 2013-02-28 05:31:13

相關問題