2016-04-13 8 views
2

İşte benim arka plan komut dosyası. Popup komutumdan ona bir mesaj gönderebiliyorum. Başka bir deyişle, konsol arka planda "merhaba" yazar. Ancak, arka plan komut dosyasından içerik komut dosyasına iletiyi alamıyorum ancak, bu iletiyi iletemiyorum. İşte içerik dosyam. Uyarı gösterilmiyor.Bir krom uzantısı ile, uzun ömürlü bir bağlantı (bağlantı noktası) kullanarak arka plan komut dosyasından içerik komut dosyasına iletiyi nasıl iletebilirim?

// content.js 

var port = chrome.runtime.connect({name:"mycontentscript"}); 

port.onMessage.addListener(function(message,sender){ 

    if (message.greeting == "hello") { 

     alert('hello'); 
    } 
}); 

Neyi yanlış yapıyorum? Teşekkürler.

cevap

0

Durumumun sizinki gibi olup olmadığını bilmiyorum, ancak arka plan sayfasının istemciye ileti gönderdiği bir Chrome uzantısı da yazdım. Benim content script yılında

, ben aşağıdakileri yapın:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { 
    sendResponse({ 
     messages : inboxMessages, 
     userId : user_id 
    }); 
}); 

Ve sonra benim içerik komut mesajı alır: In

chrome.runtime.sendMessage('requestData', this.updateData.bind(this)); 

benim background script, ben

this.updateData = function(data) { 
    //... 
} 

Umarım bu size yardımcı olur! background.js ise

0

:

chrome.runtime.onConnect.addListener(function(port){//here you've got the port 

    port.onMessage.addListener(function(msg) { 

     if (msg.greeting == "hello") { 
//and here you're making a new, unneeded port, for which nobody is listening. 
//Use the one you've got. 
      var port = chrome.tabs.connect(0, {name: "mycontentscript"}); 

      port.postMessage({greeting:"hello"}); 

      console.log('hello'); 
     } 
    }); 
}); 

Ya başlatmak chrome.tabs.connect ile arka plandan bağlayın ve sekmenin content.js içinde chrome.runtime.onConnect dinleyici koymak ya bağlanmak başlatmak Yaptığınız sekmeyi ve arka planın onConnect dinleyicisinde alınan bağlantı noktasını kullanın. Sadece bu

var port=chrome.tabs.connect(0, {name: "mycontentscript});

satırı silin.

2

Bağlantı oluşturulduktan sonra içerik komut dosyasına yalnızca postMessage bağlantısını oluşturmayı ve arka planda runtime.onConnect.addListener() bağlantı noktasını yeniden kullanmayı unutmuşsunuz gibi görünüyor.

background.js

chrome.runtime.onConnect.addListener(function(port) { 
    port.onMessage.addListener(function(msg) { 
     if (msg.greeting == "hello") { 
      port.postMessage({ greeting: "hello" }); 
      console.log('hello'); 
     } 
    }); 
}); 

content.js

var port = chrome.runtime.connect({ name: "mycontentscript" }); 
port.postMessage({greeting: "hello"}); 
port.onMessage.addListener(function(message) { 
    if (message.greeting == "hello") { 
     alert('hello'); 
    } 
}); 
İlgili konular