I'm working on a simple Chrome extension. I have something like that
/* content script */
chrome.runtime.sendMessage({msg: "marco"}, function(response){
if (response.foo){
console.log(response.foo);
}
});
/* background script */
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if (request.msg){
// sendResponse({foo: "polo"}); // works fine
// load a local JSON file
$.getJSON("path/to/file.js", function(data){
console.log("success"); // works fine
sendResponse({foo: "polo"}); // does not work
});
}
});
As you can probably see, the call to sendResponse
from the body of getJSON
's callback does not seem to be sending the response although the call to log
right above it executes perfectly. If I call sendResponse
from outside the body of getJSON
's callback, it sends the response normally.
Any idea of what might be the problem?
In the end of the listener function you must return "true" so the connection to the content script will remain opened.
In async calls listener function will end and the port will be closed immediately so sendResponse
function will do nothing.
From the documentation:
This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).