Selects the button with the id="notify" from the DOM.
Stores it in the variable notifyBtn.
2. Notification and Interval Variables
letinterval;letnotification;
interval: Stores the ID of the interval function (used for clearing the interval later).
notification: Stores the latest notification instance.
3. Click Event Listener on Button
notifyBtn.addEventListener("click",()=>{Notification.requestPermission().then((permission)=>{if (permission=="granted"){notification=newNotification("Example",{body:"This is more text for example"+Math.random(),icon:"icon.png",tag:"Example",});notification.addEventListener("error",(e)=>{console.error();});}});});
Explanation:
When the button is clicked:
Notification.requestPermission() asks for permission to display notifications.
If the user grants permission (granted), a new notification is created:
Title: "Example"
Body: "This is more text for example" + random number.
Icon: "icon.png"
Tag: "Example" (helps to prevent duplicate notifications)
Listens for error events on the notification and logs them.
4. Handling Page Visibility Changes
document.addEventListener("visibilitychange",()=>{if (document.visibilityState==="hidden"){constleaveDate=newDate();interval=setInterval(()=>{notification=newNotification("Come back",{body:`You have been gone for ${Math.round((newDate()-leaveDate)/1000)} secs, come back!`,tag:"Come back",});notification.addEventListener("error",(e)=>{console.error(e);});},100);}else{if (interval){clearInterval(interval);}if (notification){notification.close();}}});
Explanation:
visibilitychange event fires when the user switches tabs or minimizes the browser.
If the page is hidden:
Stores the time when the user left (leaveDate).
Starts an interval that creates a new notification every 100ms.
Notification says how long the user has been away in seconds.
Top comments (0)