W.K.S
W.K.S

Reputation: 10095

Chrome Extension script only runs when popup is displayed

I'm trying to develop something similar to an appointment reminder extension for Google Chrome. The extension consists of a browser action which, when clicked, displays an HTML page where the user enters the details of the appointment. At the start of the appointment, an alert should display the name of the appointment.

This extension does work but only if the browser action is active. If the browser action is turned off, then the alarm does not popup at the appointed time. I don't understand what's causing this issue.

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.');
        }
    });
});

Upvotes: 1

Views: 146

Answers (1)

Scott
Scott

Reputation: 614

I assume that you are calling chrome.alarms.create in the popup page. This registers an alarm to the defaultView (window) of the popup. It is destroyed when the popup closes.

You need to register the alarm to the background page's view:

chrome.runtime.getBackgroundPage(function(bg) {
  bg.chrome.alarms.create( ... );
});

Upvotes: 3

Related Questions