我正在尝试开发类似于Google Chrome的约会提醒扩展程序。 该扩展包含一个浏览器操作,当单击该操作时,将显示一个HTML页面,用户可在其中输入约会的详细信息。 在约会开始时,警报应显示约会的名称。
此扩展程序确实有效,但仅在浏览器操作处于活动状态时才有效。如果关闭浏览器操作,则不会在指定时间弹出警报。我不明白导致这个问题的原因。
的manifest.json
{
"manifest_version": 2,
"name": "Appointment",
"description": "",
"version": "1.0",
"background": {
"scripts": [
"js/jquery.js",
"js/Utils.js",
"js/Controller.js"
]
},
"permissions": [
"storage",
"alarms",
],
"browser_action": {
"default_icon": "icon-appointment.png",
"default_popup": "popup.html"
}
}
Controller.js
function loadAppointments(allAppointmentsLoadedCallback){
chrome.storage.sync.get("test_appointments",function(items){
allAppointments = [];
if("test_appointments" in items){
sAllAppointments = items["test_appointments"];
allAppointments = JSON.parse(sAllAppointments);
}
allAppointmentsLoadedCallback(allAppointments);
});
}
function getAppointmentScheduledAt(aUnixTime,appointmentFoundCallback){
console.log('Finding Appointment for ',new Date(aUnixTime));
loadAppointments(function(allAppointments){
for(var i=0;i<allAppointments.length;i++){
var anAppointment = allAppointments[i];
var startTime = new Date(anAppointment.startTime).getTime();
console.log('Start time is ',startTime,' and alarm time is',aUnixTime);
if(startTime == aUnixTime){
appointmentFoundCallback(anAppointment);
return;
}
}
appointmentFoundCallback(null);
});
}
chrome.alarms.onAlarm.addListener(function(anAlarm){
getAppointmentScheduledAt(anAlarm.scheduledTime,function(appointment){
if(appointment){
console.log('Found one');
alert(appointment.title);
}else{
console.log('No appointment found.');
}
});
});
答案 0 :(得分:3)
我假设你在弹出页面中调用了chrome.alarms.create
。这会向弹出窗口的defaultView
(window
)注册警报。弹出窗口关闭时会被破坏。
您需要将警报注册到背景页面的视图:
chrome.runtime.getBackgroundPage(function(bg) {
bg.chrome.alarms.create( ... );
});