Returning pass data from Background.html to popup.html
I've passed data from the background to the popup fine. However, if I return response.reply
I get undefined but if I print it out, its not undefined. It's as I expected it to be. How do I return this?
popup.html
function getURL(action){
chrome.extension.sendRequest(
{
req: "geturl",
act: action
},
function(response)
{
return response.repl开发者_运维知识库y;
});
}
background.html
function getURL(action)
{
var url = cmshttp+cmshooksurl+"?action="+action;
return url;
}
You can't return a value from asynchronous function. You need to pass the value to the next function instead (callback).
You code should look like this:
function getURL(action, callback){
chrome.extension.sendRequest(
{
req: "geturl",
act: action
},
function(response)
{
callback(response.reply);
}
);
}
Usage:
getURL("some_action", function(reply) {
console.log("reply is:", reply);
});
background.html:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.req == "geturl") {
sendResponse({reply:"reply from background"});
}
});
精彩评论