Javascript 如何在弹出窗口中保存background.html的选项?
我有个问题,我还不能解决。我有一个带有菜单和选项卡的弹出页面,还有一个设置选项卡。在“设置”选项卡上,我将一些项目保存到localstorage,其中之一是桌面通知的通知时间 注意:我没有选项页 我的扩展有这个弹出窗口和一个背景页面,它的功能是用桌面通知提醒用户。我每5、10、30分钟、1、2小时等显示一次通知,这一次应该可以在弹出页面的选项菜单中选择。问题是,如果节省了5分钟,例如,当我更新到10分钟时,background.html不会更新自己!我几乎重写了20次代码,但找不到解决方案。这是一个代码示例和一个打印屏幕,可以清楚地了解我的问题 弹出窗口: 注意:保存设置是一个按钮,在选项卡上有一个复选框,如果选中,则允许通知,否则禁用。有两个html选择标记,一个用于选择一些数据org=organization,另一个用于选择时间。notif_time_select是html select标记,在这里我选择5、10、30分钟等等 所以,每当我单击save按钮时,我都会将复选框状态保存到localstorage,并从后台页面调用一个函数以节省时间。 :bgp.setTimeparseInt$notif\u time\u select:selected.val 背景页: 为了节省时间,我使用函数setTime:Javascript 如何在弹出窗口中保存background.html的选项?,javascript,jquery,google-chrome-extension,Javascript,Jquery,Google Chrome Extension,我有个问题,我还不能解决。我有一个带有菜单和选项卡的弹出页面,还有一个设置选项卡。在“设置”选项卡上,我将一些项目保存到localstorage,其中之一是桌面通知的通知时间 注意:我没有选项页 我的扩展有这个弹出窗口和一个背景页面,它的功能是用桌面通知提醒用户。我每5、10、30分钟、1、2小时等显示一次通知,这一次应该可以在弹出页面的选项菜单中选择。问题是,如果节省了5分钟,例如,当我更新到10分钟时,background.html不会更新自己!我几乎重写了20次代码,但找不到解决方案。这是
var time = 300000; // default
function setTime(time){
this.time=time;
console.log("time set to: "+this.time);
}
之后,我使用setInterval定期显示通知
setInterval(function(){
howmanyOnline("notify",function(data){
if(data>localStorage.getItem("notifynumber")){
if (!window.webkitNotifications) { // check browser support
alert('Sorry , your browser does not support desktop notifications.');
}
notifyUser(data); // create the notification
}
if(localStorage.getItem('tweet')=='true'){
if(data>localStorage.getItem("notifynumber")){
sendTweet(data,localStorage.getItem('org'),localStorage.getItem('ck'),localStorage.getItem('cs'),localStorage.getItem('at'),localStorage.getItem('ats'));
}
}
});
},time);
setInterval内的代码工作正常,唯一的问题是
},time);
更新不好。如果我将设置更改为每10分钟显示一次通知,它将保持5分钟。唯一的方法是重新启动整个扩展。如何在不重新启动整个扩展的情况下更新setInterval的频率?谢谢你,吉姆
如果我也将notif_时间保存到localStorage,并在后台设置一个侦听器,以侦听localStorage的更改,该怎么办。有没有办法监听特定的本地存储项更改 现在,当应用程序加载时,setInterval只运行一次。如果希望interval以新的时间间隔启动,则应使用clearInterval,然后重新调用setInterval
在这里,NotifiInterval是对setInterval返回的间隔的引用,用于清除它。您问题中的源代码尚未完成,但我猜您调用了setInterval,然后在后台页面中修改了window.time。 您的window.time不是一个对象,而是一个数值,并且setInterval在调用后看不到window.time的更改。 试试这个:
function onTimeout() {
// do your notification.
setTimeout(onTimeout, time);
}
setTimeout(onTimeout, time);
这就是解决方案,我测试了3次,效果很好,谢谢@apsillers
// set a new time, wipe out the old interval, and set a new interval
function setTime(t) {
window.time = t;
clearInterval(notifInterval);
notifInterval = setInterval(makeNotification, time);
}
// set first interval
notifInterval = setInterval(makeNotification, time);
function makeNotification() {
// do what you need to make a notification
}
function onTimeout() {
// do your notification.
setTimeout(onTimeout, time);
}
setTimeout(onTimeout, time);