r/JavaScriptTips • u/Low_Mammoth_9371 • Jan 31 '23
Create desktop notifications from the browser (after obtaining user pemission) 🔔
21
Upvotes
1
1
u/Banzaye Jan 31 '23 edited Jan 31 '23
Here's a way to set alarms and notify the user with a custom notification when they are set and triggered.
Content script:
// Get the input value for the alarm time
let alarmTime = document.getElementById("alarm-time").value;
let alarmMessage = document.getElementById("task-name").value;
// Send a message to the background script with the alarm time and message
chrome.runtime.sendMessage({
title: "New Reminder",
alarmId: Date.now(),
type: "setAlarm",
iconUrl: "icon.png",
alarmTime: alarmTime,
alarmMessage: alarmMessage
}); Background script:
chrome.runtime.onMessage.addListener(function (request, sender,
sendResponse) {
if (request.type === "setAlarm") {
// Get the alarm time and message from the request
var alarmId = request.alarmId
var alarmTime = request.alarmTime;
var alarmMessage = request.alarmMessage;
// Get the current date
var currentDate = new Date();
// Append the alarm time to the current date
var alarmDate = new Date(currentDate.toDateString() + " " + alarmTime);
// Convert the alarm date to milliseconds
var alarmTimeInMs = alarmDate.getTime();
// Convert the entered time to milliseconds since the Unix epoch
// Use the chrome.alarms API to create an alarm
chrome.alarms.create(alarmId.toString(), {
when: alarmTimeInMs
});
chrome.notifications.create(`alarm-set-${alarmId.toString()}`, {
type: "basic",
title: "Alarm Set",
iconUrl: "icon.png",
message: "Reminder set for " + alarmTime,
});
chrome.alarms.onAlarm.addListener(function (alarm) {
if (alarm.name === alarmId.toString()) {
chrome.notifications.create(`myNotification-${alarmId.toString()}`, {
type: "basic",
title: "Reminder",
iconUrl: "icon.png",
message: alarmMessage,
requireInteraction: true
});
chrome.alarms.onAlarm.removeListener(arguments.callee);
}
});
}
});Also in Background script for persistance:
const onUpdate = (tabId, info, tab) => /^https?:/.test(info.url) && findTab([tab]);
findTab();
chrome.runtime.onConnect.addListener(port => {
if (port.name === 'keepAlive') {
setTimeout(() => port.disconnect(), 250e3);
port.onDisconnect.addListener(() => findTab());
}
});
async function findTab(tabs) {
if (chrome.runtime.lastError) {
/* tab was closed before setTimeout ran */
}
for (const {
id: tabId
} of tabs || await chrome.tabs.query({
url: '*://*/*'
})) {
try {
await chrome.scripting.executeScript({
target: {
tabId
},
func: connect
});
chrome.tabs.onUpdated.removeListener(onUpdate);
return;
} catch (e) {}
}
chrome.tabs.onUpdated.addListener(onUpdate);
}
function connect() {
chrome.runtime.connect({
name: 'keepAlive'
})
.onDisconnect.addListener(connect);
}Add these to the manifest:
"permissions": [
"scripting",
"activeTab",
"alarms",
"notifications"
],
"host_permissions": ["<all_urls>"]
2
u/Low_Mammoth_9371 Jan 31 '23
Code to copy below, YT tutorial here: https://youtu.be/ssUcK23bjxc