Notification with Audio in JavaScript
[Clique aqui para ler em portugus]
We always need a feedback to our user about some information, whether its a finalized registration or something removed, and today one of the best ways to give feedback to our users is with notification, so lets create a notification using javascript and stay more professional we will add an audio whenever the notification is called.
Code
First lets create the interface, well do something simple, using just HTML.
<button>Click here</button>
To display our notification, lets just create one button.
const buttonEl = document.querySelector("button");const title = "Success";const msg = "Message";const icon = "https://via.placeholder.com/50x50";const song = "notification.mp3";buttonEl.addEventListener("click", notifyMe);function notifyMe() { if (!("Notification" in window)) { alert("This browser does not support Desktop notifications"); } if (Notification.permission === "granted") { callNotify(title, msg, icon); return; } if (Notification.permission !== "denied") { Notification.requestPermission((permission) => { if (permission === "granted") { callNotify(title, msg, icon); } }); return; }}function callNotify(title, msg, icone) { new Notification(title, { body: msg, icon: icone }); new Audio(song).play();}
In our javascript code we have our constants that have the message title, the message an icon and an audio file.
For the notification, a function called notifyMe was created that will be executed whenever we click on the button.
In the notifyMe function, we first check if the browser supports notification, then we check if the user has already allowed to be notified, and if not, then we check if he hasnt denied it either, and then the notification api itself makes the request to the user checking whether or not he authorizes the sending of notification.
Finally, we have the callNotify function in which the notification is displayed with the title message and icon that we defined, and we still use the browsers own audio api so that whenever this function is called, play in the audio file.
ready simple like that.
Demo
See below for the complete working project.
if you can't see it click here and see the final result
Youtube
If you prefer to watch it, see the development on youtube.
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
See you later!
Support Me
Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso
Original Link: https://dev.to/walternascimentobarroso/notification-with-audio-in-javascript-4iao
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To