I am using the following code to send a sample message from the content script:
function sendjsontrue()
{
var arrCars = new Array("Toyota", "Mercedes", "BMW");
jsonStr = JSON.stringify(arrCars);
chrome.extension.sendRequest({greeting: jsonStr}, function(response){
console.log(response.farewell);
});
console.log("Message with header=greeting has been sent...");
}
The code in my popup.html to handle the message sent by content script, is given below–
<script>
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({notfarewell:"Not goodbye"}); .
});
</script>
The error that I am getting is given below–
Port error: Could not establish connection. Receiving end does not exist.
chrome/EventBindings:184Error in event handler for 'undefined': TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://nkmkgjckmjekpbghhildcfdlnbjeglkd/obtainformdata.js:81:25
at chrome/RendererExtensionBindings:238:13
at [object Object].dispatch (chrome/EventBindings:182:28)
at Object.<anonymous> (chrome/RendererExtensionBindings:134:27)
What have I done wrong here?
You should write the receiver code in a background page, instead of at the popup. Content scripts communicate with the background page, by default.
If you’re in need of decent documentation, have a look at: