2014-05-11 12 views
6

ho i seguenti file (gist per un facile accesso):chrome.runtime.sendMessage nello script contenuti non invia un messaggio

manifest.json

{ 
    "name": "testmessage", 
    "version": "0.1", 
    "manifest_version": 2, 
    "externally_connectable": { 
    "matches": ["*://www.google.com/*"] 
    }, 
    "background": { 
    "scripts": ["background.js"], 
    "persistent": true 
    }, 
    "content_scripts": [ 
    { 
     "matches": ["*://www.google.com/*"], 
     "js": ["content.js"] 
    } 
    ] 
} 

content.js

chrome.runtime.sendMessage(
    "eldkfaboijfanbdjdkohlfpoffdiehnb", // PUT YOUR EXTENSION ID HERE 
    "foo", 
    function (response) { 
     console.log(response); 
    } 
); 
console.log("this is content.js reporting for duty"); 

background.js

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) { 
     console.log("background.js got a message") 
     console.log(request); 
     console.log(sender); 
     sendResponse("bar"); 
    } 
); 
console.log("this is background.js reporting for duty"); 

posso vedere sia "... a rapporto" messaggi nelle rispettive console. Ma background.js non riceve un messaggio quando carichi http://www.google.com. La riga 5 in content.js stampa undefined nella console per google.com.

Quando eseguo chrome.runtime.sendMessage("eldkfaboijfanbdjdkohlfpoffdiehnb", "foo"); nella console google.com, viene visualizzato nella console background.js.

Cosa sto sbagliando?

risposta

12

Quello che stai facendo male è complicarlo troppo. Due volte.

In primo luogo, non è necessario dichiarare di essere collegabili esternamente, poiché si invia un messaggio da uno script di contenuto e non dalla stessa pagina Web.

In secondo luogo, non è neanche un messaggio esterno. I messaggi esterni servono per collegare estensioni diverse, non messaggi all'interno di un interno.

Il codice dovrebbe essere simile a questa:

content.js

chrome.runtime.sendMessage(
    "foo", 
    function (response) { 
     console.log(response); 
    } 
); 

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     console.log("background.js got a message") 
     console.log(request); 
     console.log(sender); 
     sendResponse("bar"); 
    } 
); 
Problemi correlati