Chrome存储给出未定义的存储计时器
Chrome storage giving undefined for stored timer
我正在制作一个chrome扩展,我正在使用chrome存储来存储变量。实际上,我首先从用户输入一个计时器,然后在每T秒后刷新页面,这些都是用户输入的。因此,为了存储这个时间,我使用了chrome存储,像这样:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
var currentTimer = request.timer;
if(currentTimer!=null){
currentTimer = currentTimer*1000;
alert(currentTimer);
chrome.storage.sync.set({'x': currentTimer}, function() {
console.log(currentTimer);
});
}
if(currentTimer==null){
chrome.storage.sync.get('x', function(items){
currentTimer = items.value;
});
//Here currentTimer is undefined.
}
});
谁能帮助为什么currentTimer仍然未定义。我调试了很长时间,但没有找到解决方案。
问题是,一旦页面刷新currentTimer将得到NULL值,因为它是由用户只输入一次。
当原始函数已经完成时,所有chrome.*
API回调都是异步调用的,这也意味着chrome.*
API调用后的下一个语句在回调之前执行。
-
将需要结果的代码放入回调中:
chrome.storage.sync.get('something', function(item) { setTimeout(someFunction, item.value); });
-
如果在内容脚本中需要结果,则在新消息中返回值:
- 内容脚本:
chrome.runtime.sendMessage({request: "doSomething"}); chrome.runtime.onMessage.addListener(function(msg) { if (msg.response) { // do something with the received msg.response } });
背景脚本:chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { if (msg.request == "doSomething") { var tabId = sender.tab.id, frameId = sender.frameId; chrome.storage.sync.get('something', function(item) { sendMessageToFrameId(tabId, frameId, {response: item.value}); }); } }); function sendMessageToFrameId(tabId, frameId, msg) { // 1. frameId works since Chrome 41 and throws on prior versions // 2. without frameId Chrome 45 sends the message to wrong tabs try { chrome.tabs.sendMessage(tabId, msg, {frameId: frameId}); } catch(e) { chrome.tabs.sendMessage(tabId, msg); } }
相关文章:
- 如何在窗体打开时从javascript倒计时计时器值中节省时间
- 设置倒计时计时器,IE出现问题
- MobileFirst:在客户端运行计时器作业-最佳选项
- 显示具有服务器端自动时间注销的同步倒计时计时器
- 倒计时计时器应该持续两个php页面
- 在Jquery倒计时计时器上设置每个数字的动画
- 我如何才能确保计时器设置为每天4点半,所以我不会;不用在Javascript中提及某个日期
- 如何禁用窗口.当计时器超时时,打开卸载警报
- 在Nodejs中为许多用户处理计时器
- 如果弹出窗口关闭,Javascript停止/重置计时器
- Flux Utils 存储和异步计时器
- 无法将我的计时器值存储在 cookie 中
- 清除计时器而不将其存储在 nodejs 中
- 用于在线考试系统的计时器,用于存储每个单独部分的时间
- 将倒计时计时器的当前值存储在变量中,以便在模板工具包文件中使用
- Chrome存储给出未定义的存储计时器
- 制作一个倒数计时器,其中时间存储在一个变量中
- 使用本地存储和javascript保存计时器
- setTimeout事件不'在特定变量中存储计时器id时,t触发
- 如何在cookie中存储计时器值