2012-01-13 121 views
1

我知道它已經在這裏像千次,但我現在卡住了。我讀了很多答案,並研究了code.google.com,但沒有成功。我正試圖發送一個從background.htmlcontentscript.js的Chrome擴展請求。儘管我設法讓它以另一種方式工作。卡住消息傳遞background.html >> contentscript.js(擴展名爲Chrome)

代碼中background.html

chrome.tabs.getSelected(null, function(tab) { 
    chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) { 
     console.log(response.farewell); 
    }); 
    }); 

代碼中contentscript.js

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) { 
    if (request.greeting == "hello") 
     sendResponse({farewell: "goodbye"}); 
    else 
     sendResponse({farewell: "nope"}); 
}); 

作爲通信正在向後manifest.json應該罰款和其他任何工作正常。謝謝!

+0

是contentscript收到的消息? – 2012-01-13 23:44:02

+0

不,即使我添加'alert(「嘿」);'在函數內部(request,sender,sendResponse){}'沒有任何反應。 – 2012-01-13 23:53:06

回答

0

你的代碼很好,你的觸發器肯定有問題。我使用你的代碼創建了一個簡單的擴展,它工作。將這兩位添加到您的背景和內容。然後在任何頁面上選擇「發送消息」。你應該收到一個提醒。

Background.html

var menuid = chrome.contextMenus.create({"title":"Send Message", "onclick": SendMessage, "documentUrlPatterns":["http://*/*"]}); 

function SendMessage() {   
    chrome.tabs.getSelected(null, function(tab) { 
      chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) { 
       console.log(response.farewell); 
      }); 
    }); 
} 

contentscript

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) { 
    if (request.greeting == "hello") { 
      alert('hello'); 
     sendResponse({farewell: "goodbye"}); 
     } 
    else 
     { 
      alert('goodbye'); 
     sendResponse({farewell: "nope"}); 
     } 
}); 
+0

謝謝,這個工程。但仍然不知道爲什麼其他方式沒有。我使用了動作瀏覽器的onclicked事件,它也能正常工作。 – 2012-01-16 23:22:45

相關問題