r/JavaScriptTips • • Jan 31 '23

Create desktop notifications from the browser (after obtaining user pemission) 🔔

Post image
21 Upvotes

3 comments sorted by

2

u/Low_Mammoth_9371 Jan 31 '23

Code to copy below, YT tutorial here: https://youtu.be/ssUcK23bjxc

// Ask user permission to send notifications
if ("Notification" in window) {
    
    if (Notification.permission === 'granted') {
        notify();
    } else {
        Notification.requestPermission().then((res) => {
            if (res === 'granted'){
                notify();
            } else if (res === 'denied') {
                console.log("Notifications access denied");
            } else if (res === 'default') {
                console.log("Notificiation permission not given");
            }
        })
    }

} else {
    console.error("Notification not supported");
}

function notify() {
        const notification = new Notification("New JS Tip", {
        body: `Learn how to use the Notifications API`,
        icon: './resources/logo.jpg',
        image: './resources/bell.jpg',
        vibrate: [200, 100, 200],
    });

    // Add link onclick:
    notification.addEventListener('click', () => {
        window.open('https://openjavascript.info');
    });

    // Close after 5 seconds:
    setTimeout(() => {
        notification.close();
    },5000);
}

1

u/[deleted] Jan 31 '23

this is cool

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>"]