javascript - Chrome Extension sendResponse callback value not being sent -
i'm coding chrome extension interacts gmail api (chrome 45 version) , having issues sending message background.js content-script. async aspect issue lies. how can message sent after callback?
//---------in content script--------- chrome.runtime.sendmessage({ messageid: _id }, function (response) { console.log('the respose.messagepayload is: ' + response.messagepayload); }); //---------in background script--------- chrome.runtime.onmessage.addlistener(function (request, sender, sendresponse) { getmessage('me', request.messageid, function (payload) { //i want send response here //this executes , grabs payload of data api, isn't sending message content-script sendresponse({ messagepayload: payload }); }); //this synchronous call sends message content-script //sendresponse({ messagepayload: "payload" }); return true; }); function getmessage(userid, messageid,callback) { var request = gapi.client.gmail.users.messages.get({ 'userid': userid, 'id': messageid }); request.execute(callback); }
you should sending sendresponse
function in callback.
getmessage('me', request.messageid, sendresponse);
then execute when getmessage
call completes.
function getmessage(userid, messageid, sendresponse) { var request = gapi.client.gmail.users.messages.get({ 'userid': userid, 'id': messageid }); request.execute(function(response) { sendresponse({messagepayload: response.payload}); }); }
another possible solution:
- get
tab id
sender
object. - instead of callback function send tab id
getmessage
function. - now, callback function within
getmessage
function send payload content script. - add similar
onmessage
listener in content script receive payload , want payload.
your code like:
//---------in background script--------- chrome.runtime.onmessage.addlistener(function (request, sender,sendresponse) { getmessage('me', request.messageid, sender.tab.id); }); function getmessage(userid, messageid, tabid) { var request = gapi.client.gmail.users.messages.get({ 'userid': userid, 'id': messageid }); request.execute(function(response) { // whatever response want sent // below url explains response object // https://developers.google.com/gmail/api/v1/reference/users/messages#resource // assuming want send payload chrome.tabs.sendmessage(tab.id, {messagepayload: response.payload}); }); } //---------in content script--------- chrome.runtime.sendmessage({ messageid: _id }); chrome.runtime.onmessage.addlistener(function (request, sender,sendresponse) { // verify request getmessage callback // because listen request extension if (request.messagepayload) { console.log('the respose.messagepayload is: ' + request.messagepayload); } });
i hope helps.
Comments
Post a Comment