问题
I have the a onMessage.addListener function like this:
chrome.runtime.onMessage.addListener(function (r, s, sendResponse) {
if (r.action == "read") {
readManga(request, function () {
sendResponse({});
}, true);
}
if (r.action == "write") {
readManga(request, function () {
sendResponse({});
}, true);
}
if (request.action == "update") {
$.each(request.list, function (index, val) {
resetManga(val, function () {}, false);
});
saveList();
refreshUpdate();
sendResponse({});
}
if (request.action == "release") {
releaseImplentationFromId(request.id, function (mirrorName) {
updateMirrors(function () {
sendResponse({
mirror : mirrorName
});
});
return true
});
}
}
(this is an excerpt, but it's working code and please ignore all the if's, I should have used case since long ago)
Each time I use the callback function sendResponse
(again, I need to rename it, but lets ignore that) as defined in the documentation is never used unless I have return true
after it's execution. Is this really necessary or I just found a dirty hack and I'm doing something wrong?
回答1:
This is the expected behavior and clearly stated in the documentation:
This function [
sendResponse
] becomes invalid when the event listener returns, unless you returntrue
from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end untilsendResponse
is called).
Your function updateMirrors
is apparently asynchronous: the callback function does not get executed immediately but is sent into a queue. So, you're not returning true "after" its execution, you are actually hitting return true
before sendResponse
.
Therefore, it's necessary to tell Chrome "expect an answer later".
来源:https://stackoverflow.com/questions/24398813/do-i-have-to-call-return-true-each-time-i-use-onmessage-addlistener-responsecall