Here's the implementation of chrome.extension.sendRequest (found by putting a breakpoint in an extension then typing 'chrome.extension.sendRequest' into the Console). Note near the bottom that the sender waits for a response on a port then .disconnect()s the port. - Michael
function (targetId_opt, request, responseCallback_opt) {
var targetId = extensionId;
var responseCallback = null;
var lastArg = arguments.length - 1;
if (typeof(arguments[lastArg]) == "function")
responseCallback = arguments[lastArg--];
request = arguments[lastArg--];
if (lastArg >= 0 && typeof(arguments[lastArg]) == "string")
targetId = arguments[lastArg--];
if (lastArg != -1)
throw new Error("Invalid arguments to sendRequest.");
var port = chrome.extension.connect(targetId,
{name: chromeHidden.kRequestChannel});
port.postMessage(request);
port.onDisconnect.addListener(function() {
// For onDisconnects, we only notify the callback if there was an error
try {
if (chrome.extension.lastError && responseCallback)
responseCallback();
} finally {
port = null;
}
});
port.onMessage.addListener(function(response) {
try {
if (responseCallback)
responseCallback(response);
} finally {
port.disconnect();
port = null;
}
});
}