我有一个 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 个值)
最佳答案
我假设 sendRequest
是一个异步方法(很像 Ajax 调用)。该脚本不会停止并等待响应。
唯一的解决方案是在回调中调用需要响应的其他函数。
关于javascript - 这个 JavaScript 中发生了什么,我该如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7169236/