我有一个chrome扩展程序,其中包含一个可以执行的javascript文件。 javascript文件调用background.html:
action.js
var action = "";
chrome.extension.sendRequest({method: "getLocalStorage", key: "action"},
function(response) {
alert(response.data);
action = response.data;
});
alert('action:'+action);
并在 background.html:
中chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({});
我得到的行为是一个警告框,上面写着“action:
”,然后是一个警告框,上面写着“video
”,这是正确的行动价值。
为什么这些警告框显示乱序,为什么变量action
没有获得response.data
值?是否与sendRequest
方法的延迟有关?如何使脚本等待,以便我可以获得值? (我将需要多次执行此请求 - 我需要请求4个值)
答案 0 :(得分:3)
我认为sendRequest
是一种异步方法(很像Ajax调用)。脚本不会停止并等待响应。
唯一的解决方案是调用其他需要回复内部回调的函数。