Thursday, July 31, 2025

Javascript Module 44

  Module 44 : Javascript Notifications and Permissions API. - Understanding Notifications API

🔷 What is the Notifications API?

The Notifications API allows web applications to send system-level notifications to the user's device (similar to push notifications in mobile apps) even when the webpage is not in focus.

              










🔶 Key Use Cases:

Chat/messaging apps (e.g., "You have a new message")

News updates (e.g., "Breaking News")

Task reminders (e.g., "Your meeting starts in 5 minutes")

E-commerce (e.g., "Your order has been shipped")


Syntax:

new Notification(title, options);

🔑 Parameters:

title (string): The title of the notification (mandatory).

options (object): Additional details (optional):

body: Text of the notification.

icon: URL of an icon to show.

image: Large image to show.

tag: Prevents duplicate notifications.

requireInteraction: Keeps the notification open until user interacts.


 Example:

if (Notification.permission === 'granted') { new Notification('Hello!', { body: 'You have a new message.', icon: 'message-icon.png' }); }


Part 2:

Permission Handling

🔷 Why Permissions Matter

Before showing notifications, the browser must get permission from the user.


Check and Request Permission:

if (Notification.permission === 'default') { Notification.requestPermission().then(permission => { if (permission === 'granted') { new Notification('Thanks!', { body: 'You allowed notifications.' }); } }); }

 Permission Values:

'granted' – User allowed notifications.

'denied' – User blocked notifications.

'default' – User hasn't made a choice yet.


 Part 3: Permissions API (for other permissions too)

🔷 What is the Permissions API?

Lets you query and observe the state of permissions for features like notifications, geolocation, camera, microphone, etc.

🔧 Example:

navigator.permissions.query({ name: 'notifications' }).then(result => { console.log(result.state); // 'granted', 'denied', or 'prompt' });


Part 4: Full

Notification Workflow



    


            


function sendNotification(title, message, iconUrl) { // Step 1: Check for Notification support if (!('Notification' in window)) { alert('This browser does not support notifications.'); return; } // Step 2: Check current permission if (Notification.permission === 'granted') { new Notification(title, { body: message, icon: iconUrl }); } else if (Notification.permission === 'default') { // Step 3: Request permission Notification.requestPermission().then(permission => { if (permission === 'granted') { new Notification(title, { body: message, icon: iconUrl }); } else { alert('Notification permission denied.'); } }); } else { alert('Notification permission has been denied.'); } }


 Use Case : Chat App Alert

function showNewMessageNotification(username, message) { if (Notification.permission === 'granted') { new Notification(`${username} sent a message`, { body: message, icon: 'chat-icon.png', tag: 'chat-msg' }); } }

tag allows grouping:

It ensures that duplicate notifications aren't created when multiple updates come from the same user.


   Exercises:

🔸 Exercise 1: Simple Notification

Create a button on a webpage labeled “Notify Me”.

When clicked, it should show a notification with a custom title and message.

Expected Output:

document.getElementById('notifyBtn').addEventListener('click', () => { sendNotification('Hey!', 'Thanks for clicking Notify Me.', 'icon.png'); });


🔸 Exercise 2: Notification Based on Time

                     










Ask the user to set a reminder time.

Show a notification after that delay using setTimeout.

Expected Output:

function remindUser(message, delayInSeconds) { setTimeout(() => { sendNotification('Reminder', message, 'reminder-icon.png'); }, delayInSeconds * 1000); } remindUser('Time to drink water!', 10); // Notifies after 10 seconds


🔸 Exercise 3: Permissions Monitoring

Display the current status of notification permissions on the page.

Automatically update the status if it changes.

Expected Output:

navigator.permissions.query({ name: 'notifications' }).then(permissionStatus => { document.getElementById('status').innerText = permissionStatus.state; permissionStatus.onchange = () => { document.getElementById('status').innerText = permissionStatus.state; }; });


 Explanation & Behind the Scenes

 How Browser Handles Notifications:

Permission Layer: Managed by the browser to protect users from spam.

Service Layer: Notification created with title, body, and other metadata.

Delivery Layer: Rendered by the system or browser notification UI.

        Practices:

Ask for permission only after user interacts.

Do not spam users with too many notifications.

Use tag, silent, and requireInteraction wisely.

Clean and short messages get better attention.


 Research & Insights

 Cross-Browser Support:

                 










Fully supported in most modern browsers: Chrome, Edge, Firefox.

Safari has limited support and often prefers Push APIs.

Mobile browser notifications are often restricted (Push API preferred).

Security Considerations:

HTTPS is required for Notifications API.

Requesting permissions too early (e.g., on page load) often leads to denial.

📊 UX Research:

Users respond better to timely, relevant, and personalized notifications.

Poor use of notifications leads to opt-out and user churn.


🔹 Introduce with Examples:

"Have you ever seen a website send you a message when you’re not looking at the tab? That’s the Notifications API in action."

🔹 Use Interactive Demos:

Let learners try:

<button onclick="sendNotification('Hi there!', 'This is your demo notification', 'icon.png')">Click Me</button>

🔹 Explain User Privacy:

Discuss importance of only requesting permission when needed, and how overuse can make users distrust your site.


   Summary

             








   


Feature

Description

Notifications API

Show system notifications to the user

Permissions API

Check and observe permission states

requestPermission()

Ask user for notification access

navigator.permissions.query

Query any permission status

Use Case

Chat, reminders, alerts, background events




No comments:

Post a Comment

Javascript Module 78

  Javascript   Module 78 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test...