Thursday, July 31, 2025

Javascript Module 44

 




Javascript  Module 44


If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 


https://onlinecourses2024for.blogspot.com/p/contact-us.html/

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




Tuesday, July 29, 2025

Javascript Module 43

 



Javascript Module 43


If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 


https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 43

  Module 43 : Clipboard API 


1. What is the Clipboard API?

The Clipboard API is a modern asynchronous API available in JavaScript used for:

                           









   

Reading text from the clipboard: readText()

Writing text to the clipboard: writeText()

 Note: Clipboard access is only available in secure contexts (HTTPS) and often requires user gestures like a button click.


2. Security Considerations

The API works only on HTTPS or localhost.

Clipboard read operations may be blocked unless triggered by user interaction.

Access may prompt for permission.

if (!navigator.clipboard) { console.log("Clipboard API not supported!"); }


 3. Clipboard API Methods

               

πŸ”Έ navigator.clipboard.writeText(text)

Copies a given string to the clipboard.

✅ Example:

<button id="copyBtn">Copy Text</button> <input type="text" id="copyInput" value="Hello Clipboard API!"> <script> document.getElementById("copyBtn").onclick = function() { const inputText = document.getElementById("copyInput").value; navigator.clipboard.writeText(inputText) .then(() => alert("Text copied to clipboard!")) .catch(err => console.error("Copy failed:", err)); }; </script>


πŸ”Έ navigator.clipboard.readText()

Reads text content from the clipboard.

✅ Example:

<button id="pasteBtn">Paste Text</button> <input type="text" id="pasteInput" placeholder="Paste here"> <script> document.getElementById("pasteBtn").onclick = function() { navigator.clipboard.readText() .then(text => { document.getElementById("pasteInput").value = text; }) .catch(err => console.error("Paste failed:", err)); }; </script>


 4. Building a Clipboard Tool

Objective:

Build a mini tool with the following features:

Copy input text

Paste into another field

HTML + JS Code:

<h3>Clipboard Lab</h3> <textarea id="textInput" rows="3" placeholder="Type something..."></textarea><br> <button onclick="copyText()">Copy</button> <button onclick="pasteText()">Paste</button> <textarea id="outputArea" rows="3" placeholder="Pasted content..."></textarea> <script> function copyText() { const text = document.getElementById("textInput").value; navigator.clipboard.writeText(text) .then(() => alert("Copied!")) .catch(err => console.error("Copy error:", err)); } function pasteText() { navigator.clipboard.readText() .then(text => { document.getElementById("outputArea").value = text; }) .catch(err => console.error("Paste error:", err)); } </script>

πŸ” Explanation:

User writes in the first box.

On clicking "Copy", text is stored in clipboard.

On clicking "Paste", it’s fetched and inserted into the second box.


🧠 5. Exercises 

πŸ“ Exercise 1: Copy Email Address

 Create a button that copies an email address to the clipboard.

                 











<p>Email: <span id="email">example@mail.com</span></p> <button onclick="copyEmail()">Copy Email</button> <script> function copyEmail() { const email = document.getElementById("email").innerText; navigator.clipboard.writeText(email) .then(() => alert("Email copied!")) .catch(err => console.error(err)); } </script>

Exercise 2: Detect Clipboard Support

 Add a check to inform users if their browser doesn’t support clipboard.

if (!navigator.clipboard) { alert("Your browser doesn't support Clipboard API!"); }


  6. Research.   Use Cases

✅ Common Applications:

Use Case

Example

Social sharing

"Copy link to post"

Form autofill

Paste from clipboard into forms

Code copying

“Copy code” buttons on documentation pages

Online tools

Text manipulation and editors (like Notion or Grammarly)


    Research:

Browsers like Chrome and Edge allow clipboard access only with user gestures.

On Firefox, readText() prompts for permission every time.

Clipboard API may be limited in Safari or mobile browsers.

Use Permissions API to check access (experimental):

navigator.permissions.query({ name: "clipboard-read" }).then(result => { console.log(result.state); // granted | denied | prompt });


πŸ”§ 7. Debugging Tips

                


Problem

Cause

Solution

navigator.clipboard is undefined

Insecure HTTP page

Use HTTPS or localhost

Permission denied

No user interaction

Use click event

Clipboard not working on mobile

Partial support

Check browser compatibility



✅ Summary

Clipboard API is asynchronous, secure, and powerful.

Use writeText() to copy and readText() to paste.

Always handle permission errors gracefully.

Build practical tools (copy buttons, paste forms, etc.) using the API.


Review Questions

                

What are the two main methods of the Clipboard API?

Why must clipboard operations be in response to user actions?

Write a code snippet that copies a paragraph’s text to clipboard.

How do you detect if Clipboard API is supported?

Describe one use case for readText().




Sunday, July 27, 2025

Javascript Module 42



 Javascript Module 42


If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 


https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 42

  Module 42 : Javascript Geolocation

API. 

πŸ“š Theory & Concepts

✅ What is Geolocation?

Geolocation refers to the identification of the  geographic location of an object, such as a smartphone or computer. In JavaScript, this is done through the navigator.geolocation object.









✅ Core Methods

Method

Description

getCurrentPosition()

Gets the user's current location once.

watchPosition()

Continuously monitors position changes.

clearWatch()

Stops watching for location changes.



 Example with Explanation

function getUserLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); } else { console.log("Geolocation is not supported by this browser."); } } function showPosition(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; console.log("Latitude: " + latitude + " | Longitude: " + longitude); } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: console.log("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: console.log("Location information is unavailable."); break; case error.TIMEOUT: console.log("The request to get user location timed out."); break; case error.UNKNOWN_ERROR: console.log("An unknown error occurred."); break; } } // Call the function getUserLocation();


  Explanation:

navigator.geolocation: Built-in object that provides access to location services.

getCurrentPosition(success, error):

success is the callback function that receives the location.

error is the callback function that handles failures.

position.coords.latitude / longitude: The actual coordinates.

Error handling is crucial for fallback behaviors.

Exercise: Display Location on Google Maps












🎯 Goal:

Display the user's current location using Google Maps with a marker.

✅ Example:

<!DOCTYPE html> <html> <head> <title>Geolocation Map</title> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script> </head> <body> <h2>My Location</h2> <div id="map" style="width:100%;height:400px;"></div> <script> function initMap(latitude, longitude) { const userLocation = { lat: latitude, lng: longitude }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 15, center: userLocation }); new google.maps.Marker({ position: userLocation, map: map }); } function getLocationAndMap() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { const lat = position.coords.latitude; const lng = position.coords.longitude; initMap(lat, lng); }, function(error) { console.log("Error: ", error.message); }); } else { alert("Geolocation not supported."); } } getLocationAndMap(); </script> </body> </html>

Replace YOUR_API_KEY with your actual Google Maps API key.


🧠 Research Insight

How does geolocation work?

GPS: Most accurate; uses satellite data.

















Wi-Fi Positioning: Uses Wi-Fi hotspots for estimating location.

IP Address: Approximate location based on your IP.

Cell Tower Triangulation: Mobile networks use tower distance.


Privacy Consideration


Browsers ask user permission before sharing location. Always respect the user's decision and explain why the location is needed.


     Instructor.             Notes

  Suggested

Introduce use cases: Food delivery, Uber, weather.

Live demo using getCurrentPosition().

Discuss browser permission prompts.

Error simulation: Disable location to see error cases.

Integrate with Google Maps for a complete app experience.

 Discussion Topics:

Why does geolocation sometimes fail indoors?

Compare getCurrentPosition() vs watchPosition().

How can apps use location for better UX?


Exercise

Create a webpage that:

Shows user’s coordinates.

Monitors changes using watchPosition().












Displays updates on the page.

✅ Starter Code:

<p id="output">Waiting for location...</p> <script> const output = document.getElementById("output"); if (navigator.geolocation) { const watchId = navigator.geolocation.watchPosition( (pos) => { output.innerText = `Latitude: ${pos.coords.latitude}, Longitude: ${pos.coords.longitude}`; }, (err) => { output.innerText = `Error: ${err.message}`; } ); // To stop watching: // navigator.geolocation.clearWatch(watchId); } else { output.innerText = "Geolocation not supported."; } </script>


🧠  Review

Questions 

What is the difference between getCurrentPosition() and watchPosition()?

What are the common sources of location in Geolocation API?

How does the Geolocation API handle privacy and user permission?

What are some use cases for this API?

How do you integrate location data with a map?


    Summary

Concept

Explanation

Geolocation API

Allows access to user's geographic location

getCurrentPosition()

Retrieves location once

watchPosition()

Tracks location over time

Permissions

Browsers prompt user before allowing access

Use Cases

Maps, tracking, weather, local services


✅ Assignment

Build a mini weather app:

Get the user's location.











Use the coordinates to call a weather API like OpenWeatherMap.

Display current weather info (temperature, humidity, etc.).


πŸ“š Additional References

 Web Docs - Geolocation API

Google Maps JavaScript API

OpenWeatherMap API



Saturday, July 26, 2025

Javascript Module 41

 



Javascript Module 41


If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 


https://onlinecourses2024for.blogspot.com/p/contact-us.html/

javascript Module 41

  Module 41 : Local Storage and Session Storage. 

πŸ“š 1. Introduction to Web Storage

Web Storage is a browser feature that allows web applications to store data locally within the user's browser, without needing a backend database or cookies.

              










Types of Web Storage:

Storage Type

Lifespan

Scope

Capacity

Accessible From

localStorage

Until manually cleared

Same origin

~10 MB

Any tab/session

sessionStorage

Until tab is closed

Tab-specific

~5 MB

Only same tab



 2. Syntax

2.1 localStorage API

// Store data localStorage.setItem("username", "rehana"); // Retrieve data let user = localStorage.getItem("username"); // Remove item localStorage.removeItem("username"); // Clear all localStorage.clear();

2.2 sessionStorage API

// Store data sessionStorage.setItem("cart", "Apple, Banana"); // Retrieve data let cartItems = sessionStorage.getItem("cart"); // Remove item sessionStorage.removeItem("cart"); // Clear all sessionStorage.clear();


 3. Deep Conceptual Differences












Feature

localStorage

sessionStorage

Persistence

Permanent until cleared

Cleared when tab is closed

Scope

Shared across tabs of same origin

Isolated to the specific browser tab

Use Case

User settings, theme, auth tokens

Form data for multi-step forms



 4. Use Case Examples

Example 1: Remember Theme with localStorage

<button onclick="changeTheme()">Toggle Theme</button> <script> function changeTheme() { let theme = document.body.classList.toggle("dark") ? "dark" : "light"; localStorage.setItem("site-theme", theme); } window.onload = function() { const savedTheme = localStorage.getItem("site-theme"); if (savedTheme === "dark") document.body.classList.add("dark"); }; </script>

✅ Explanation: The theme persists even after closing and reopening the browser.


 Example 2: Temporary Form Auto-Fill with sessionStorage

<input type="text" id="name" placeholder="Enter your name"> <script> const input = document.getElementById("name"); // Save as user types input.addEventListener("input", () => { sessionStorage.setItem("name", input.value); }); // Restore on reload (same tab) window.onload = () => { const savedName = sessionStorage.getItem("name"); if (savedName) input.value = savedName; }; </script>

✅ Explanation: Name is remembered as long as the tab stays open.


5. Build a Persistent Notes App

 Objective:








Create a small notes-taking web app using localStorage to save notes even after the browser is closed.

 Steps:

Create an HTML page with a textarea and a "Save" button.

On clicking Save, store the note in localStorage.

On page load, retrieve and display the note.

Code:

<textarea id="note" rows="5" cols="30" placeholder="Write your note..."></textarea> <button onclick="saveNote()">Save Note</button> <script> function saveNote() { const note = document.getElementById("note").value; localStorage.setItem("myNote", note); } window.onload = () => { const savedNote = localStorage.getItem("myNote"); if (savedNote) { document.getElementById("note").value = savedNote; } }; </script>

✅ Outcome:

Note remains even after browser restart.


2: Multi-Tab Form Save (sessionStorage)

Create a multi-step form that saves inputs temporarily using sessionStorage.

Steps:

Build a 2-step form (Name and Email).

Save values in sessionStorage after each step.

Autofill if user reloads in the same tab.


πŸ“˜ 6. Exercises

✅ Exercise 1:

Build a simple login page. On successful login, store the username in localStorage. Show a welcome message on page load if the user is remembered.

✅ Exercise 2:

Create a product cart using sessionStorage. Add/remove products dynamically and display them on the page.

✅ Exercise 3:

Make a “last visited” tracker using localStorage. On every visit, show the last visit time.


 Research Insights











 Browser Storage Limits

localStorage: ~5-10MB per domain depending on browser.

sessionStorage: Smaller, ~5MB.

Storage is synchronous, meaning it can block the main thread for large data.

πŸ”’ Security Notes

Data is stored in plain text – never store sensitive data like passwords.

Use JSON.stringify() and JSON.parse() to store/retrieve objects.

πŸ›‘ Best Practices

Use try...catch to handle storage errors.

Don’t overload with too much data.

Always check for storage support:

if (typeof(Storage) !== "undefined") { // Safe to use localStorage/sessionStorage } else { alert("Sorry, your browser does not support Web Storage..."); }


πŸ“š Summary

Feature

Use Case

API Example

localStorage

Theme settings, persistent login

localStorage.setItem()

sessionStorage

Form progress, temp user data

sessionStorage.setItem()



πŸ“Ž Additional

Web Docs - localStorage

HTML5 Rocks Guide to Web Storage (Archived)

Can I use - Web Storage


πŸ“Create a "User Profile Page"











 that uses both localStorage and sessionStorage:

localStorage to save user's theme, language preference.

sessionStorage to save temporary inputs like phone number (auto-cleared on tab close).


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...