I am trying to develop a chrome extension and I trying to communicate between the content script and background.html page. I am storing some values(local storage) in the background.html and getting it whenever i need it in the content script. My listener listens to the request that i send from contentscript and fetches the data and sends it back to the contentscript. But when I receive it in contentscript my data becomes "undefined".
This is my code:
background.html:
chrome.extension.onRequest.addListener(
function(request,sender,sendresponse){
if(request.Meta == '_service'){
/* return _getServiceOfAddon("_service");
}
else if(request.Meta == 'setAddOnService'){
_setServiceAddon("_service",request.messageContent);
}*/
if(request.messageContent){
console.log('message content for setservice : '+request.messageContent);
_setServiceOfAddon("_service",request.messageContent);
}
else{
//return _getServiceOfAddon("_service");
console.log('message content for getservice : '+request.messageContent);
var temp = _getServiceOfAddon("_service");
console.log('getting service as '+ temp);
sendresponse({ mydata : temp });
}
}
});
Content Script:
Tagg.sideBar.backgroundInteraction.prototype.s开发者_StackOverflow社区endMessageToBackground = function(meta,messagecontent){
if(!meta){
chrome.extension.sendRequest(
{
Meta:'testingMessageConfirmation',
messageContent:'This is a testing message sent from content script to background'
},
function(response){}
);
}
else{
chrome.extension.sendRequest(
{
Meta:meta,
messageContent:messagecontent
},
function(response){
//if(!response.data){
console.log('response data received as : '+ response.mydata);
return response;
// }
}
);
}
}
The response.data that i receive in the contentscripts is "undefined". Can anybody point the mistake that I am making here? This seems to be very simple but I could not find the exact point where I make the mistake.
First of, what exact type of object does _getServiceOfAddon()
return? I'm sure the intent is to return a string, but with message passing one possible cause of an undefined
error is trying to pass things like classes, functions, etc. You might want to try console.log
on the response
object.
The more likely possibility is using return
, which doesn't work great with asynchronous stuff like message passing. You should probably assign the return value to its target some other way, like using this
or passing a reference to the DOM object or assigning it to a hash like settings["_service"]
.
In other words, Tagg.sideBar.backgroundInteraction.sendMessageToBackground()
will always return undefined
as is. The callback function you have in chrome.extension.sendRequest()
returns the response
to chrome.extension.sendRequest
, not sendMessageToBackground()
. Remember that a function returns a value to its caller, and in this case its caller is sendRequest()
精彩评论