Google chrome extension Chrome扩展sendRequest并返回响应
我正在开发一个chrome扩展。我有一个函数,它从本地存储中检索一个JOSN字符串并返回它 它不能正常工作,这是我的代码Google chrome extension Chrome扩展sendRequest并返回响应,google-chrome-extension,local-storage,Google Chrome Extension,Local Storage,我正在开发一个chrome扩展。我有一个函数,它从本地存储中检索一个JOSN字符串并返回它 它不能正常工作,这是我的代码 function getstore() { var all = {}; chrome.extension.sendRequest({method: "getlist", key: "" }, function(response) { all = JSON.parse(response.data); console.log(all
function getstore()
{
var all = {};
chrome.extension.sendRequest({method: "getlist", key: "" }, function(response) {
all = JSON.parse(response.data);
console.log(all); //it prints the JSON properly
return all; //
});
}
但每当我像这样调用该函数时:
var old_a = getstore();// old_a should hold the JSON returned by getstore()
console.log(old_a);
但是这里“old_a”的值变得不确定。实际上,您没有从方法
getstore()
返回任何内容
sendRequest方法有一个回调函数,它在异步函数完成时调用该函数。方法签名如下所示:
chrome.extension.sendRequest(options, responseCallback)
所以responseCallback是您添加为最后一个参数的函数
function(response) {
all = JSON.parse(response.data);
console.log(all); //it prints the JSON properly
return all; // No sense in returning from a callback method, it will do nothing and will never be catched anywhere.
}
因此,您要做的是:
function getstore()
{
chrome.extension.sendRequest({method: "getlist", key: "" }, function(response) {
var old_a = JSON.parse(response.data);
// Use the json object here.
console.log(old_a);
});
}
非常感谢!