JSFiddle - React, Tailwind, and code Playground
HTML
<section>
<h1>
Notification constructor
</h1>
<button id="normal">
Normal
</button>
<button id="silent">
Silent
</button>
<button id="custom">
Custom Sound
</button>
</section>
<section>
<h1>
Service Worker (not working on JS fiddle)
</h1>
<button id="swnormal">
Normal
</button>
</section>
JavaScript
const EXTERNAL_SOUND = "https://lab.humanoids.be/tetris.MP3";
const showNotification = async (options) => {
const perm = await Notification.requestPermission()
if(perm === "granted") {
const notif = new Notification("Test notification", options);
for(const p in options) {
console.log(p, notif[p] === options[p]);
}
}
else {
console.error("Can not play sound because permission was not granted.");
}
};
const showSWNotification = async (options) => {
const perm = await Notification.requestPermission()
if(perm === "granted" && navigator.serviceWorker) {
const sw = await navigator.serviceWorker.ready;
sw.showNotification("Test notification", options);
}
else {
console.error("Can not play sound because permission was not granted.");
}
};
document.getElementById("normal").addEventListener("click", () => showNotification());
document.getElementById("silent").addEventListener("click", () => showNotification({ silent: true }));
document.getElementById("custom").addEventListener("click", () => showNotification({ sound: EXTERNAL_SOUND}));
document.getElementById("swnormal").addEventListener("click", () => showSWNotification());