Klassik
Klassik

Reputation: 141

Google Chrome extension alarm at specific time

Good morning dear developers,

I am developing a small Google Chrome Extention but I am not sure if this is the right way. Maybe I am a bit confused with all the background pages, event paes, content scripts and so on.

What is this extension going to do? Alarm: Manipulate the current opened tabs CSS and play a sound. The time is always the same (wether you in America or Europe or wherever). This is not the main thing. I used this kind of "architecture" with a similar extention but there I had to do something active (clicks etc.). This extention here is totally in the background.

{
    "manifest_version": 2,
    "version": "0.1",
    "name": "Alarm whatever",
    "permissions": ["alarms"],
    "icons": {
        "16": "icon.png",
        "48": "icon.png",
        "128": "icon.png"
    },
    "content_scripts": [{
        "js": ["jquery.js", "script.js"],
        "matches": ["http://*/*", "https://*/*"]
    }],
   "background": {
     "scripts": [ "background.js" ],
     "persistent": false 
   } 
}

background.js

// When to ring
var now = new Date(), minutes = 50, seconds = 0;
var timestamp = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), minutes, seconds);
var whenToRing = (timestamp.getTime() - now.getTime());

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if(request.action == 'createAlarm')
    {   
        // Create
        chrome.alarms.create('theAlarm', {
            // Wann soll der Alarm gefeuert werden?
            // Angabe in Millisekunden
            when: whenToRing,
        }); 
    }
});

chrome.alarms.onAlarm.addListener(function(alarm) {
    if (alarm.name === 'theAlarm') 
    {
        // send a message to the script.js to manipulate the CSS and play sound
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          chrome.tabs.sendMessage(tabs[0].id, {action: 'doAlarm'})   
        });
    }
});

script.js

$(document).ready(function()
{
    chrome.runtime.sendMessage({action: 'createAlarm'});

    chrome.runtime.onMessage.addListener(
  function(resp, sender, sendResponse) {

        if(resp.action == 'doAlarm')
        {
            // CSS and SOUND here           
        }
    });
}); 

I've shortened the CSS and Sound. The time is set to the current hour to test this extention.

Some ideas? Thank you!

Upvotes: 3

Views: 2388

Answers (1)

chenop
chenop

Reputation: 5143

Old question but I think answer is important.

The creation of the alarm looks ok. Here is how I would calculate the whenToRing for example if you want an alarm event on 08:00 am.

var whenToRing = new Date().setHours(8);

Upvotes: 2

Related Questions