13 Understanding Chrome Extensions Alarms

The chrome.alarms API is an API use to schedule code to execute at a preset time and/or periodically. See the Chrome Alarms API documentation for more info.

How is Chrome Alarms API different from setInterval or setTimeout?

setInterval and setTimeout are functions that are used to schedule code to run in the future and periodically as well. However the difference become apparent when we start talking about the persistence. Chrome Alarms still run even when the computer is put to sleep. They can still execute their code at the desired time even after the browser is closed and reopened before that time.

Each alarms has and name that can be used to get information about that time it started, when it will run next and it’s interval rate.

How To Declare Chrome Alarms in the Manifest.json

{
...
"permissions":[
"alarms"
],
...
}

How to set and Chrome Alarm

Photo by Kasia Derenda on Unsplash

You would use usually write this code in your extension pages and background scripts. You CANNOT get or set an alarm in content scripts.

// Documentation - https://developer.chrome.com/docs/extensions/reference/api/alarms#type-AlarmCreateInfo
const callback = () => console.log("Callback function");
const milliseconds = 30 * 1000; //30seconds

const options = {
// Length of time in minutes after which the
// onAlarm event should fire.
delayInMinutes:2,

// If set, the onAlarm event should fire every
// periodInMinutes minutes after the initial
// event specified by when or delayInMinutes.
// If not set, the alarm will only fire once.
periodInMinutes:4,

// Time at which the alarm should fire, in milliseconds
// past the epoch (e.g. Date.now() + n).
when: Date.now() + milliseconds,
}

chrome.alarms.create('alarm-name', options, callback);

How to get Chrome Alarm Details

Alarms have the following information about them; nameperiodInMinutes and scheduledTimescheduledTime is the number milliseconds past the epoch.

Get One Alarm

// use callback way
chrome.alarms.get('alarm-name', (alarm) => {
console.log(alarm);
});

// or use async/await
const alarm = await chrome.alarms.get('alarm-name');
console.log(alarm);

Get All Alarms

// use callback way
chrome.alarms.getAll((alarms) => {
console.log('All alarms', alarms);
});

// or use async/await
const alarms = await chrome.alarms.getAll();
console.log(alarms);

How to remove Alarms

Sometime you’d want to remove alarms

Remove one alarm

As long as you know the name of the alarm you set you can remove a specific alarm.

// use callback way
chrome.alarms.clear('alarm-name', (wasCleared) => {
console.log('wasCleared', wasCleared); // wasCleared is a boolean
});

// or use async/await
const wasCleared = await chrome.alarms.clear('alarm-name');
console.log(wasCleared);

Remove all alarms

// use callback way
chrome.alarms.clearAll((wasCleared) => {
console.log('wasCleared', wasCleared); // wasCleared is a boolean
});

// or use async/await
const wasCleared = await chrome.alarms.clearAll();
console.log(wasCleared);

How to listen for Chrome Alarms

Now that we are able to get and set alarms. How is code execute when the alarms run on the preset time? This is where the chrome.alarms.onAlarm.addListener function comes into play. When whenever an alarms hits the time to run this listener function fires.

You would write this code in your background script.

chrome.alarms.onAlarm.addListener((alarm) => {
const name = alarm.name;
if(name == 'alarm-name'){
// your code.
}
})

Sample Project

We are going to make a water reminder chrome extensions. A user will set when the alarms should first remind them and the interval for subsequent reminders. For this will need 4 four files popup.htmlpopup.jsmanifest.json and background.js

You see some functions using the chrome.action API. It is just to display NOW text reminder on the extension icon. To now more about the chrome.action API you can look the Google Chrome’s documentation or better yet read our article on it. 🫡 8 Understanding Chrome Extensions Action

manifest.json

{
"name": "Water Reminder",
"manifest_version": 3,
"version": "1.0.0.0",
"permissions": [
"alarms"
],
"action": {
"default_popup": "popup.html",
"default_title": "Water Reminder"
},
"background": {
"service_worker": "background.js"
}
}

background.js

// Listen for alarms

chrome.alarms.onAlarm.addListener((alarm) => {

// https://developer.chrome.com/docs/extensions/reference/api/action
chrome.action.setBadgeTextColor({ color: "#FFFFFF" });
chrome.action.setBadgeBackgroundColor({ color: "#4287f5" });
chrome.action.setBadgeText({ text: "NOW" });
console.log(alarm);
});

popup.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
padding: 10px 20px;
margin: 0 auto;
width: 300px;
height: 400px;
}

button {
font-weight: 700;
border: none;
padding: 10px 20px;
color: white;
background: #4287f5;
border-radius: 30px;
cursor: pointer;
}

form {
justify-content: center;
display: flex;
flex-direction: column;
width: 100%;
}

input {
margin: 10px;
padding: 4px 10px;
border-radius: 20px;
border-width: 2px;
border-color: rgb(209, 209, 209);
width: 50%;
}
</style>
</head>

<body>
<form>
<h1>💦 Water Reminder 💦</h1>
<p>Start Time</p>
<input type="datetime-local" name="start" value="" />
<br />
<p>Repeat me evert (x) minutes</p>
<input type="number" min="1" max="60" name="repeat" value="3" placeholder="Reminds in minutes" />
<br />
<button type="submit">Set Alarm</button>
</form>
<br />
<button id="clear">Clear Alarm</button>
<script type="text/javascript" src="./popup.js"></script>
</body>

</html>

popup.js

document.querySelector('form').onsubmit = (e) => {
e.preventDefault();
const start = e.target.start.value;
const repeat = e.target.repeat.value;

// validation check
if (!start || !repeat) return alert('Please set start time and repeat interval');

const date = new Date(start);
const periodInMinutes = parseInt(repeat);
const when = date.getTime();

// if you want it to run once do NOT include 'periodInMinutes'
chrome.alarms.create('water', { when: when, periodInMinutes: periodInMinutes }, () => alert('Water Reminder Set'));
}

// clearing alarm
document.getElementById('clear').onclick = (e) => {
chrome.alarms.clear('water', (wasCleared) => {
if (wasCleared) {
// https://developer.chrome.com/docs/extensions/reference/api/action
chrome.action.setBadgeText({ text: "" })
}
});
}

Chrome Extension

Leave a Reply

Your email address will not be published. Required fields are marked *

More Articles & Posts