Simple Alarm with Notification

May 25, 2017

Before reading this post setup your Firefox so you can run WebExtensions in your browser.

In this blog we will be exploring more about how to create a simple Periodic Alarm using Alarm WebExtension API. So Whenever we get an alarm instead of triggering it with sounds we will be sending small push notification.

Step 1 : Creating the Alarm for Running first time.

So the very first thing is we have to set when should our first Alarm be called. So after that for every next 30 mintues we can create the next alarm. Lets say I created the alarm at 2:30 AM and then it will be ringing again at 3:00 AM so next should be at 3:30 AM, so from 3:10 to 3:50 I have switched off my system no alarm is created, so to avoid this when I open my browser next time freshly I am creating the alarm in the next nearest 30 Mins. There are two API to know when an Extension is installed and when browser is started there are as follows

  • browser.runtime.onInstalled
  • browser.runtime.onStartup

so in the below code I have added a listener method for these two actions.


// Add a method what to happen when Addon is installed
browser.runtime.onInstalled.addListener(handleInstalled);

// Add a method what to happen when browser starts
browser.runtime.onStartup.addListener(handleStartup);

Then whenever these actions happen I set my first alarm using the below code.


browser.alarms.create("Alarm-Unique-Name-for-Extension", {
  when,
  periodInMinutes
});

Here when is the time in long, the time when the alarm should be created. And periodInMinutes is the time interval when next alarm should get created, so I gave it as 30 which means in next 30 mintues I alarm will get triggered again.

Step 2: Capturing the alarm

The next step after creating the alarm is to Capture it.


// Add a method when a alarm is triggerd
browser.alarms.onAlarm.addListener(handleAlarm);

So there is a method called handleAlarm which will get the alarm Details object. In this object we will be having the alarm “name”, then “scheduledTime” and then “periodInMinutes”.

Step 3: Create Notification

On capturing the alarm we are creating a basic notification using Notfication API. Here we have to give


browser.notifications.create("notification-name", {
    "type": "basic",
    "iconUrl": browser.extension.getURL("path-of-image"),
    "title": "title-for-notification",
    "message": "Message-for-Notification"
  });

The detailed post regarding creating the Notification is previously discussed in another post

For the Extension to run we need two permission which has to be mentioned in our manifest.json


"permissions" : [
        "notifications",
        "alarms"
        ],

Checkout the code in github and share your thoughts.

Read Other Related Posts about : Mozilla

  • MozillaTN SNSCT WebExtension Workshop
  • Creating ShortenURL Maker Addon
  • Creating Simple Easy Searcher Using ContextMenu
  • Comments

    comments powered by Disqus