[Go to site: main page, start]

0% found this document useful (0 votes)
2 views63 pages

Asynchronous JavaScript

The document provides an overview of asynchronous JavaScript, explaining its importance for non-blocking code execution and detailing methods such as callbacks, promises, and async/await. It contrasts synchronous and asynchronous programming, highlighting the complexities of managing multiple tasks concurrently and the issue of 'callback hell.' Additionally, it introduces the Fetch API for making HTTP requests and demonstrates error handling in asynchronous operations, along with exercises for practical application.

Uploaded by

Sweety Sonia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views63 pages

Asynchronous JavaScript

The document provides an overview of asynchronous JavaScript, explaining its importance for non-blocking code execution and detailing methods such as callbacks, promises, and async/await. It contrasts synchronous and asynchronous programming, highlighting the complexities of managing multiple tasks concurrently and the issue of 'callback hell.' Additionally, it introduces the Fetch API for making HTTP requests and demonstrates error handling in asynchronous operations, along with exercises for practical application.

Uploaded by

Sweety Sonia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Asynchronous JavaScript

Asynchronous JavaScript is an essential concept that allows


your code to execute tasks in a non-blocking manner. This
means you can perform other operations while waiting for a
particular task, like fetching data from an API, to complete.
There are several ways to handle asynchronous operations in
JavaScript, including:
 Callbacks: Functions passed as arguments to other
functions and called once the task is complete.
 Promises: Objects representing the eventual completion
(or failure) of an asynchronous operation and its resulting
value.
 Async/Await: Syntax that makes asynchronous code
appear more like synchronous code, improving
readability and maintainability.
The differences between synchronous and asynchronous
programming.
Synchronous Programming
Sequential Execution: Tasks are executed one after the other,
in the order they appear.
Blocking: Each task must complete before the next one starts.
If a task takes a long time, it blocks the entire program.
Simple to Understand: Since tasks are executed in a
predictable order, it's easier to write and debug synchronous
code.
Example:
```javascript
[Link]("Task 1");
[Link]("Task 2");
[Link]("Task 3");

// Output:
// Task 1
// Task 2
// Task 3
```

Asynchronous Programming
Concurrent Execution: Tasks can be initiated without
waiting for other tasks to complete. Tasks can run
simultaneously, or "in parallel."
Non-Blocking: Tasks can start while others are still running,
which means the program doesn't get held up by slow tasks.
More Complex: Writing and debugging asynchronous code
can be more challenging due to the need to manage multiple
tasks running concurrently.
Example with Callbacks:
```javascript
[Link]("Task 1");

setTimeout(() => {
[Link]("Task 2 (Asynchronous)");
}, 2000);

[Link]("Task 3");

// Output:
// Task 1
// Task 3
// Task 2 (Asynchronous) - after a 2-second delay
```

Example with Promises:


```javascript
[Link]("Task 1");

const asyncTask = new Promise((resolve, reject) => {


setTimeout(() => {
resolve("Task 2 (Asynchronous)");
}, 2000);
});

[Link]((message) => {
[Link](message);
});

[Link]("Task 3");

// Output:
// Task 1
// Task 3
// Task 2 (Asynchronous) - after a 2-second delay
```

Example with Async/Await:


```javascript
async function asyncFunction() {
[Link]("Task 1");

const asyncTask = new Promise((resolve, reject) => {


setTimeout(() => {
resolve("Task 2 (Asynchronous)");
}, 2000);
});

const result = await asyncTask;


[Link](result);

[Link]("Task 3");
}

asyncFunction();

// Output:
// Task 1
// (After a 2-second delay)
// Task 2 (Asynchronous)
// Task 3
```
The concept of callbacks and the challenge often referred to as
"callback hell."

Callbacks
Definition: A callback is a function passed as an argument to
another function and is executed after the main function has
completed its task.
Usage: Callbacks are commonly used in asynchronous
programming to handle tasks like reading files, making API
requests, or performing database operations.

Here's a simple example of a callback function:

```javascript
function greet(name, callback) {
[Link]("Hello " + name);
callback();
}

function sayGoodbye() {
[Link]("Goodbye!");
}

greet("Alice", sayGoodbye);

// Output:
// Hello Alice
// Goodbye!
```

In this example, `sayGoodbye` is passed as a callback to the


`greet` function and is executed after the greeting.

Callback Hell
Definition: "Callback hell" (also known as "Pyramid of
Doom") refers to the situation where multiple nested callbacks
make the code hard to read and maintain.
Symptoms: As more callbacks are nested within each other,
the code becomes increasingly difficult to understand and
debug due to the deeply nested structure.
Example of Callback Hell:
```javascript
doTask1(function(result1) {
doTask2(result1, function(result2) {
doTask3(result2, function(result3) {
doTask4(result3, function(result4) {
doTask5(result4, function(result5) {
// Continue nesting more callbacks...
});
});
});
});
});
```

In this example, each task is dependent on the completion of


the previous task, leading to deeply nested callbacks that are
challenging to manage.
Solutions to Avoid Callback Hell
1. Promises: Promises provide a cleaner way to handle
asynchronous tasks, allowing you to chain operations without
deep nesting.

```javascript
doTask1()
.then(result1 => doTask2(result1))
.then(result2 => doTask3(result2))
.then(result3 => doTask4(result3))
.then(result4 => doTask5(result4))
.catch(error => [Link](error));
```
2. Async/Await: The `async` and `await` keywords simplify
asynchronous code, making it look more like synchronous
code.

```javascript
async function performTasks() {
try {
const result1 = await doTask1();
const result2 = await doTask2(result1);
const result3 = await doTask3(result2);
const result4 = await doTask4(result3);
const result5 = await doTask5(result4);
} catch (error) {
[Link](error);
}
}

performTasks();
```
Exercise 1. Write a Promise-based function that simulates
fetching user data from a server. Use .then() and .catch() to
handle successful and failed responses.
Here's a Promise-based function that simulates fetching user
data from a server. The function `fetchUserData` returns a
Promise that resolves with user data after a delay or rejects
with an error message if something goes wrong.

```javascript
function fetchUserData(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Simulate fetching user data
const success = [Link]() > 0.2; // 80% chance
of success
if (success) {
resolve({
userId: userId,
name: "John Doe",
email: "[Link]@[Link]",
age: 30
});
} else {
reject("Failed to fetch user data.");
}
}, 2000); // Simulate a 2-second delay
});
}

// Using the function with .then() and .catch()

fetchUserData(1)
.then(userData => {
[Link]("User data fetched successfully:", userData);
})
.catch(error => {
[Link]("Error:", error);
});
```
In this example:
- The `fetchUserData` function simulates an API call by
returning a Promise.
- Inside the Promise, we use `setTimeout` to simulate a delay.
- The success of the operation is determined by a random
number, with an 80% chance of success.
- If successful, the Promise resolves with user data.
- If it fails, the Promise rejects with an error message.
- We use `.then()` to handle the successful response and
`.catch()` to handle any errors.
Introduction to Fetch API
The Fetch API is a modern way to make HTTP requests in
JavaScript. It's a cleaner and more powerful alternative to the
older `XMLHttpRequest`. By default, the Fetch API returns a
Promise that resolves to the Response object representing the
request's response.

Using Fetch API with Async/Await


By combining the Fetch API with `async/await`, you can write
asynchronous code that looks and behaves more like
synchronous code. Here's an example of how to fetch user
data from an API using `async/await`:
```javascript
// Define an async function to fetch user data
async function fetchUserData(userId) {
try {
// Make the HTTP request using Fetch API
const response = await
fetch(`[Link]

// Check if the response is OK (status code 200-299)


if (![Link]) {
throw new Error("Network response was not ok");
}

// Parse the response as JSON


const userData = await [Link]();

// Handle the fetched user data


[Link]("User data fetched successfully:", userData);
} catch (error) {
// Handle any errors that occurred during the fetch
[Link]("Error fetching user data:", error);
}
}

// Call the async function with a user ID


fetchUserData(1);
```
Explanation:
1. Async Function: `fetchUserData` is defined as an `async`
function, allowing us to use `await` within it.
2. Fetch Request: We use `await` to wait for the `fetch` call to
complete. This pauses the execution of the function until the
Promise resolves.
3. Response Check: We check if the response is OK using
`[Link]`. If not, we throw an error.
4. Parse JSON: We use `await` again to wait for the response
to be parsed as JSON.
5. Handle Data:We handle the fetched user data by logging it
to the console.
6. Error Handling:We use a `try...catch` block to handle any
errors that may occur during the fetch or JSON parsing.

Comparison to Using `.then()` and `.catch()`


Using `async/await` can make your code more readable and
easier to maintain compared to chaining multiple `.then()`
calls:
With `.then()` and `.catch()`:
```javascript
fetch(`[Link]
.then(response => {
if (![Link]) {
throw new Error("Network response was not ok");
}
return [Link]();
})
.then(userData => {
[Link]("User data fetched successfully:", userData);
})
.catch(error => {
[Link]("Error fetching user data:", error);
});
```

Both approaches achieve the same result, but `async/await`


tends to be more straightforward and easier to read, especially
for more complex asynchronous workflows.

Exercise 1: Rewrite the Previous Promise-Based User Data


Fetch Function Using Async/Await

Here's the updated function using `async/await`:

```javascript
async function fetchUserData(userId) {
try {
// Simulate a delay to fetch user data
await new Promise(resolve => setTimeout(resolve,
2000));
// Simulate a successful response 80% of the time
if ([Link]() > 0.2) {
const userData = {
userId: userId,
name: "John Doe",
email: "[Link]@[Link]",
age: 30
};
[Link]("User data fetched successfully:",
userData);
} else {
throw new Error("Failed to fetch user data.");
}
} catch (error) {
[Link]("Error:", error);
}
}

// Call the function with a user ID


fetchUserData(1);
```
Exercise 2: Use the Fetch API to Make a GET Request to a
Public API and Display Results in the Console

Here's an example of how to use the Fetch API to make a


GET request to a public API (JSONPlaceholder) and display
the results in the console:

```javascript
async function fetchPublicAPIData() {
try {
const response = await
fetch('[Link]

// Check if the response is OK (status code 200-299)


if (![Link]) {
throw new Error("Network response was not ok");
}

const data = await [Link]();


[Link]("Public API data fetched successfully:",
data);
} catch (error) {
[Link]("Error fetching public API data:", error);
}
}

// Call the function to fetch public API data


fetchPublicAPIData();
```

In this example:
Exercise 1: The `fetchUserData` function simulates fetching
user data with a delay and a success probability. It uses
`async/await` for asynchronous operations and error handling.
Exercise 2: The `fetchPublicAPIData` function makes a GET
request to the JSONPlaceholder API to fetch user data. It
handles the response, checks for errors, parses the data as
JSON, and logs the results to the console.

Error Handling and Building a Simple Async App


Handling errors effectively is essential when working with
asynchronous code. I'll demonstrate how to handle errors
using `async/await` and then guide you through building a
simple asynchronous app.
Error Handling with Async/Await
To handle errors in `async/await` functions, we use
`try...catch` blocks. This allows us to catch and handle any
errors that occur during asynchronous operations.

an example of error handling with `async/await`:

```javascript
async function fetchData(url) {
try {
const response = await fetch(url);
if (![Link]) {
throw new Error("Network response was not ok");
}
const data = await [Link]();
[Link]("Data fetched successfully:", data);
} catch (error) {
[Link]("Error fetching data:", error);
}
}

fetchData('[Link]
```
In this example, the `fetchData` function makes an HTTP
request using the Fetch API and handles any errors that might
occur during the process.
Building a Simple Async App
Let's build a simple asynchronous app that fetches and
displays user data from a public API (JSONPlaceholder).
We'll use `async/await` for asynchronous operations and
handle errors effectively.

1. HTML Structure:
Create a basic HTML structure with a button to trigger the
data fetch and a div to display the results.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Async App</title>
</head>
<body>
<h1>Async User Data Fetch</h1>
<button id="fetchButton">Fetch User Data</button>
<div id="userData"></div>

<script src="[Link]"></script>
</body>
</html>
```

2. JavaScript Code:
Add the following JavaScript code in a file named
`[Link]` to handle the data fetch and display the results:

```javascript

[Link]('fetchButton').addEventListener('cl
ick', fetchUserData);

async function fetchUserData() {


const userDataDiv =
[Link]('userData');
[Link] = "Loading...";
try {
const response = await
fetch('[Link]
if (![Link]) {
throw new Error("Network response was not ok");
}
const userData = await [Link]();
displayUserData(userData);
} catch (error) {
[Link] = "Error fetching user data: "
+ [Link];
}
}

function displayUserData(userData) {
const userDataDiv =
[Link]('userData');
[Link] = `
<h2>${[Link]}</h2>
<p>Email: ${[Link]}</p>
<p>Username: ${[Link]}</p>
<p>Phone: ${[Link]}</p>
<p>Website: ${[Link]}</p>
`;
}
```

Explanation:
1. HTML Structure: The HTML file contains a button and a
div to display the fetched user data.
2. JavaScript Code:
- The `fetchUserData` function is triggered when the button
is clicked.
- The function uses `async/await` to fetch user data from
the JSONPlaceholder API.
- If the fetch is successful, the user data is displayed using
the `displayUserData` function.
- If an error occurs, an error message is displayed.
● Exercise: Build a simple "User Profile Fetcher" app:
o Create an HTML page with a button and a section to
display user data.
o Use Fetch with async/await to call a public API and
retrieve user data.
o Display the data dynamically on the page.
o Handle errors and show appropriate error messages
on the page.
Step 1: Create an HTML Page

Create a basic HTML page with a button to fetch user data


and a section to display the fetched data.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>User Profile Fetcher</title>
<style>
body {
font-family: Arial, sans-serif;
}
#userData {
margin-top: 20px;
}
.error {
color: red;
}
</style>
</head>
<body>
<h1>User Profile Fetcher</h1>
<button id="fetchButton">Fetch User Profile</button>
<div id="userData"></div>

<script src="[Link]"></script>
</body>
</html>
```

Step 2: Add JavaScript to Fetch User Data

Create a `[Link]` file to handle the fetching of user data


using Fetch API with `async/await`.

```javascript
[Link]('fetchButton').addEventListener('cl
ick', fetchUserData);
async function fetchUserData() {
const userDataDiv =
[Link]('userData');
[Link] = "Loading...";

try {
const response = await
fetch('[Link]
if (![Link]) {
throw new Error("Network response was not ok");
}
const userData = await [Link]();
displayUserData(userData);
} catch (error) {
[Link] = `<p class="error">Error
fetching user data: ${[Link]}</p>`;
}
}

function displayUserData(userData) {
const userDataDiv =
[Link]('userData');
[Link] = `
<h2>${[Link]}</h2>
<p>Email: ${[Link]}</p>
<p>Username: ${[Link]}</p>
<p>Phone: ${[Link]}</p>
<p>Website: ${[Link]}</p>
`;
}
```

Explanation:
1. HTML Page:
- The HTML page contains a button (`Fetch User Profile`)
and a div (`userData`) to display the fetched user data.
- Basic styling is added to improve the appearance.

2. JavaScript Code:
- An event listener is added to the button to trigger the
`fetchUserData` function when clicked.
- The `fetchUserData` function uses `async/await` to fetch
user data from the JSONPlaceholder API.
- If the fetch is successful, the `displayUserData` function is
called to display the fetched data.
- If an error occurs, an error message is displayed in the
`userData` div.

With this setup, clicking the "Fetch User Profile" button will
fetch user data from the public API and display it on the page.
Errors are handled gracefully, and appropriate error messages
are shown to the user.

Real-time data allows systems to process and deliver


information immediately as events occur, rather than with a
delay. This is crucial for applications that require up-to-the-
minute updates, such as financial trading platforms, online
gaming, chat applications, and real-time notifications.
Real-Time Data
Real-time data is data that is delivered immediately after
collection. There is no delay in the timeliness of the
information provided. Real-time processing involves
continuous input, processing, and output of data, which
provides up-to-date information that can be acted upon
immediately.
WebSockets
WebSockets are a protocol for full-duplex communication
channels over a single TCP connection. Unlike HTTP, where
the client requests and the server responds, WebSockets
enable two-way communication between the client and the
server. This makes WebSockets ideal for applications that
require real-time interaction.
How WebSockets Work
1. Connection Establishment: A WebSocket connection is
initiated by the client with an HTTP request. The server
responds with an upgrade header, switching the connection to
a WebSocket.
2. Communication: Once established, both client and server
can send messages to each other independently at any time.
3. Connection Termination: Either the client or the server
can close the connection when it's no longer needed.

Example Use Cases for WebSockets


- Live Chat Applications: Enables real-time messaging
between users.
- Online Gaming: Facilitates real-time gameplay interactions.
- Live Financial Tickers: Provides real-time updates of stock
prices or cryptocurrency values.
- Collaborative Tools: Allows multiple users to interact with
shared documents or projects in real time.

Example Code for a WebSocket Client


a simple example of how to create a WebSocket client in
JavaScript:
```javascript
// Create a new WebSocket connection
const socket = new WebSocket('[Link]

// Event listener for when the connection is opened


[Link]('open', (event) => {
[Link]('WebSocket connection opened:', event);

// Send a message to the server


[Link]('Hello Server!');
});

// Event listener for when a message is received from the


server
[Link]('message', (event) => {
[Link]('Message from server:', [Link]);
});

// Event listener for when the connection is closed


[Link]('close', (event) => {
[Link]('WebSocket connection closed:', event);
});
// Event listener for when an error occurs
[Link]('error', (event) => {
[Link]('WebSocket error:', event);
});
```

In this example:
- A new WebSocket connection is created with `new
WebSocket('[Link]
- Event listeners are added to handle the opening of the
connection, receiving messages, closing the connection, and
errors.
- The client sends a message to the server using
`[Link]('Hello Server!')`.

WebSockets provide a powerful way to enable real-time


communication between clients and servers, making them
ideal for a wide range of applications that require
instantaneous data updates.
Sure! Let's set up a WebSocket connection to a sample server
and log messages received in real-time. We'll use the public
WebSocket server `[Link] for this
exercise.
HTML Structure

Create a basic HTML file with a button to initiate the


WebSocket connection and an area to display messages.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>WebSocket Example</title>
<style>
#messages {
margin-top: 20px;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h1>WebSocket Example</h1>
<button id="connectButton">Connect to
WebSocket</button>
<div id="messages"></div>

<script src="[Link]"></script>
</body>
</html>
```

JavaScript Code

Create a `[Link]` file to handle the WebSocket connection


and log messages received in real-time.

```javascript
[Link]('connectButton').addEventListener
('click', connectWebSocket);

function connectWebSocket() {
const socket = new WebSocket('[Link]
const messagesDiv =
[Link]('messages');
[Link] = "Connecting...";

// Event listener for when the connection is opened


[Link]('open', (event) => {
[Link]('WebSocket connection opened:', event);
[Link] += "<p>WebSocket
connection opened.</p>";

// Send a message to the server


[Link]('Hello Server!');
});

// Event listener for when a message is received from the


server
[Link]('message', (event) => {
[Link]('Message from server:', [Link]);
[Link] += `<p>Message from server:
${[Link]}</p>`;
});

// Event listener for when the connection is closed


[Link]('close', (event) => {
[Link]('WebSocket connection closed:', event);
[Link] += "<p>WebSocket
connection closed.</p>";
});

// Event listener for when an error occurs


[Link]('error', (event) => {
[Link]('WebSocket error:', event);
[Link] += `<p>WebSocket error: $
{[Link]}</p>`;
});
}
```

Explanation:
1. HTML Structure: The HTML page contains a button
(`Connect to WebSocket`) and a div (`messages`) to display
messages received from the WebSocket server.
2. JavaScript Code:
- An event listener is added to the button to trigger the
`connectWebSocket` function when clicked.
- The `connectWebSocket` function creates a new
WebSocket connection to the public server
`[Link]
- Event listeners handle the WebSocket events: `open`,
`message`, `close`, and `error`.
- When the connection is opened, a message is sent to the
server, and a log message is displayed on the page.
- When a message is received from the server, it is logged
and displayed on the page.
- When the connection is closed or an error occurs,
appropriate messages are displayed.

Building Real-Time Notifications with the Notifications


API

The Notifications API allows web applications to send


notifications to the user even when the web page is not in
focus. This is useful for real-time notifications such as
messages, alerts, or updates.
Step-by-step guide to building real-time notifications using
the Notifications API:

Step 1: Requesting Permission


Before you can send notifications, you need to request
permission from the user.

```javascript
if ([Link] === 'default' ||
[Link] === 'undefined') {
[Link]().then(permission => {
if (permission === 'granted') {
[Link]('Notification permission granted.');
} else {
[Link]('Notification permission denied.');
}
});
}
```

Step 2: Sending a Notification


Once permission is granted, you can send a notification.

```javascript
function sendNotification(title, options) {
if ([Link] === 'granted') {
new Notification(title, options);
} else {
[Link]('Notification permission not granted.');
}
}

// Example usage
sendNotification('Hello!', {
body: 'This is a real-time notification.',
icon: 'path/to/[Link]'
});
```

Step 3: Integrating with Real-Time Data (Using


WebSockets)
To demonstrate real-time notifications, let's integrate with a
WebSocket server.

1. HTML Structure:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Real-Time Notifications</title>
</head>
<body>
<h1>Real-Time Notifications with WebSockets</h1>
<button id="connectButton">Connect to
WebSocket</button>

<script src="[Link]"></script>
</body>
</html>
```

2. JavaScript Code:

```javascript

[Link]('connectButton').addEventListener
('click', connectWebSocket);

async function requestNotificationPermission() {


if ([Link] === 'default' ||
[Link] === 'undefined') {
return await [Link]();
}
return [Link];
}

function sendNotification(title, options) {


if ([Link] === 'granted') {
new Notification(title, options);
} else {
[Link]('Notification permission not granted.');
}
}

function connectWebSocket() {
const socket = new
WebSocket('[Link]

[Link]('open', async (event) => {


[Link]('WebSocket connection opened:', event);
const permission = await
requestNotificationPermission();
if (permission === 'granted') {
sendNotification('WebSocket Connected', {
body: 'You are now connected to the WebSocket
server.',
icon: 'path/to/[Link]'
});
}
[Link]('Hello Server!');
});

[Link]('message', (event) => {


[Link]('Message from server:', [Link]);
sendNotification('New Message', {
body: `Message from server: ${[Link]}`,
icon: 'path/to/[Link]'
});
});

[Link]('close', (event) => {


[Link]('WebSocket connection closed:', event);
sendNotification('WebSocket Disconnected', {
body: 'The WebSocket connection has been closed.',
icon: 'path/to/[Link]'
});
});

[Link]('error', (event) => {


[Link]('WebSocket error:', event);
sendNotification('WebSocket Error', {
body: 'An error occurred with the WebSocket
connection.',
icon: 'path/to/[Link]'
});
});
}
```

Explanation:
1. HTML Structure:
- The HTML page contains a button (`Connect to
WebSocket`) that will initiate the WebSocket connection.

2. JavaScript Code:
- The `requestNotificationPermission` function requests
permission from the user to send notifications.
- The `sendNotification` function sends a notification if
permission is granted.
- The `connectWebSocket` function establishes a WebSocket
connection to the server.
- Event listeners handle the WebSocket events (`open`,
`message`, `close`, `error`) and send appropriate notifications
based on the events.

By following these steps, you can build real-time notifications


using the Notifications API and integrate them with a
WebSocket server to receive real-time updates.
Building a Basic Notification System
Let's build a basic notification system that requests
notification permission from the user, displays a notification
when a WebSocket message is received, and customizes the
notification with a title, message, and icon.
Step 1: Create an HTML Page

Create a basic HTML page with a button to connect to the


WebSocket server.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Notification System</title>
<style>
body {
font-family: Arial, sans-serif;
}
#messages {
margin-top: 20px;
}
.error {
color: red;
}
</style>
</head>
<body>
<h1>WebSocket Notification System</h1>
<button id="connectButton">Connect to
WebSocket</button>
<div id="messages"></div>

<script src="[Link]"></script>
</body>
</html>
```

Step 2: Add JavaScript to Handle Notifications and


WebSocket Connection

Create a `[Link]` file to request notification permission,


handle WebSocket connection, and display notifications.

```javascript
[Link]('connectButton').addEventListener
('click', connectWebSocket);

async function requestNotificationPermission() {


if ([Link] === 'default' ||
[Link] === 'undefined') {
return await [Link]();
}
return [Link];
}

function sendNotification(title, options) {


if ([Link] === 'granted') {
new Notification(title, options);
} else {
[Link]('Notification permission not granted.');
}
}

function connectWebSocket() {
const socket = new WebSocket('[Link]
const messagesDiv =
[Link]('messages');

[Link] = "Connecting...";

[Link]('open', async (event) => {


[Link]('WebSocket connection opened:', event);
[Link] += "<p>WebSocket
connection opened.</p>";

const permission = await


requestNotificationPermission();
if (permission === 'granted') {
sendNotification('WebSocket Connected', {
body: 'You are now connected to the WebSocket
server.',
icon: 'path/to/[Link]' // Replace with the path to
your icon
});
}
[Link]('Hello Server!');
});

[Link]('message', (event) => {


[Link]('Message from server:', [Link]);
[Link] += `<p>Message from server:
${[Link]}</p>`;

sendNotification('New Message', {
body: `Message from server: ${[Link]}`,
icon: 'path/to/[Link]' // Replace with the path to your
icon
});
});

[Link]('close', (event) => {


[Link]('WebSocket connection closed:', event);
[Link] += "<p>WebSocket
connection closed.</p>";

sendNotification('WebSocket Disconnected', {
body: 'The WebSocket connection has been closed.',
icon: 'path/to/[Link]' // Replace with the path to your
icon
});
});

[Link]('error', (event) => {


[Link]('WebSocket error:', event);
[Link] += `<p
class="error">WebSocket error: ${[Link]}</p>`;

sendNotification('WebSocket Error', {
body: 'An error occurred with the WebSocket
connection.',
icon: 'path/to/[Link]' // Replace with the path to your
icon
});
});
}
```

Explanation:
1. HTML Page:
- The HTML page contains a button (`Connect to
WebSocket`) and a div (`messages`) to display messages from
the WebSocket server.
- Basic styling is added to improve the appearance.

2. JavaScript Code:
- The `requestNotificationPermission` function requests
notification permission from the user.
- The `sendNotification` function sends a notification if
permission is granted.
- The `connectWebSocket` function establishes a WebSocket
connection to the public server `[Link]
- Event listeners handle WebSocket events (`open`,
`message`, `close`, `error`) and display appropriate
notifications.
- Customize the notification with a title, message, and icon.

By following these steps, you can build a basic notification


system that requests notification permission from the user,
displays notifications when a WebSocket message is received,
and customizes the notification with a title, message, and icon.

Building a Real-Time Data and Notification Application


### Building a Real-Time Data and Notification Application

Combining real-time data and notifications can create


powerful, responsive applications that keep users informed
and engaged. Let's build a simple application that fetches real-
time data using WebSockets and sends notifications using the
Notifications API.

### Step 1: Create the HTML Structure

We'll start by setting up the basic HTML structure, which


includes a button to connect to the WebSocket server and a
section to display messages.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Real-Time Data and Notification App</title>
<style>
body {
font-family: Arial, sans-serif;
}
#messages {
margin-top: 20px;
}
.error {
color: red;
}
</style>
</head>
<body>
<h1>Real-Time Data and Notification App</h1>
<button id="connectButton">Connect to
WebSocket</button>
<div id="messages"></div>

<script src="[Link]"></script>
</body>
</html>
```

### Step 2: Add JavaScript to Handle WebSocket Connection


and Notifications

Create a `[Link]` file to manage the WebSocket connection


and handle notifications.

```javascript
[Link]('connectButton').addEventListener
('click', connectWebSocket);

async function requestNotificationPermission() {


if ([Link] === 'default' ||
[Link] === 'undefined') {
return await [Link]();
}
return [Link];
}

function sendNotification(title, options) {


if ([Link] === 'granted') {
new Notification(title, options);
} else {
[Link]('Notification permission not granted.');
}
}

function connectWebSocket() {
const socket = new WebSocket('[Link]
const messagesDiv =
[Link]('messages');

[Link] = "Connecting...";

[Link]('open', async (event) => {


[Link]('WebSocket connection opened:', event);
[Link] += "<p>WebSocket
connection opened.</p>";

const permission = await


requestNotificationPermission();
if (permission === 'granted') {
sendNotification('WebSocket Connected', {
body: 'You are now connected to the WebSocket
server.',
icon: 'path/to/[Link]' // Replace with the path to
your icon
});
}
[Link]('Hello Server!');
});

[Link]('message', (event) => {


[Link]('Message from server:', [Link]);
[Link] += `<p>Message from server:
${[Link]}</p>`;

sendNotification('New Message', {
body: `Message from server: ${[Link]}`,
icon: 'path/to/[Link]' // Replace with the path to your
icon
});
});

[Link]('close', (event) => {


[Link]('WebSocket connection closed:', event);
[Link] += "<p>WebSocket
connection closed.</p>";

sendNotification('WebSocket Disconnected', {
body: 'The WebSocket connection has been closed.',
icon: 'path/to/[Link]' // Replace with the path to your
icon
});
});

[Link]('error', (event) => {


[Link]('WebSocket error:', event);
[Link] += `<p
class="error">WebSocket error: ${[Link]}</p>`;

sendNotification('WebSocket Error', {
body: 'An error occurred with the WebSocket
connection.',
icon: 'path/to/[Link]' // Replace with the path to your
icon
});
});
}
```

Explanation:
1. HTML Structure: The HTML page contains a button
(`Connect to WebSocket`) and a div (`messages`) to display
messages from the WebSocket server. Basic styling is added
to improve the appearance.
2. JavaScript Code:
- Notification Permission: The
`requestNotificationPermission` function requests permission
from the user to send notifications.
- Sending Notifications: The `sendNotification` function
sends a notification if permission is granted.
- WebSocket Connection: The `connectWebSocket` function
establishes a WebSocket connection to the public server
`[Link]
- Event Listeners: Event listeners handle WebSocket events
(`open`, `message`, `close`, `error`) and display appropriate
notifications.
● Exercise: Build a “Real-Time Stock Ticker” or “Live
Weather Update” app:
o Use WebSockets to receive data in real time.
o Display the data on the web page and send a
notification when a specific event occurs.
Let's build a "Live Weather Update" app that uses WebSockets
to receive data in real time, displays the data on a web page,
and sends a notification when a specific event occurs. For this
example, we'll use a public WebSocket server for live weather
updates.
Step 1: Create the HTML Structure
Create a basic HTML page with a section to display the
weather updates and a button to connect to the WebSocket
server.

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Live Weather Update App</title>
<style>
body {
font-family: Arial, sans-serif;
}
#weatherUpdates {
margin-top: 20px;
}
.error {
color: red;
}
</style>
</head>
<body>
<h1>Live Weather Update App</h1>
<button id="connectButton">Connect to
WebSocket</button>
<div id="weatherUpdates"></div>

<script src="[Link]"></script>
</body>
</html>
```
Step 2: Add JavaScript to Handle WebSocket Connection,
Display Weather Updates, and Send Notifications

Create a `[Link]` file to manage the WebSocket connection,


display weather updates, and handle notifications.
```javascript
[Link]('connectButton').addEventListener
('click', connectWebSocket);

async function requestNotificationPermission() {


if ([Link] === 'default' ||
[Link] === 'undefined') {
return await [Link]();
}
return [Link];
}

function sendNotification(title, options) {


if ([Link] === 'granted') {
new Notification(title, options);
} else {
[Link]('Notification permission not granted.');
}
}

function connectWebSocket() {
// Replace with a public WebSocket server for live weather
updates
const socket = new WebSocket('[Link]
websocket-server');
const weatherUpdatesDiv =
[Link]('weatherUpdates');

[Link] = "Connecting...";

[Link]('open', async (event) => {


[Link]('WebSocket connection opened:', event);
[Link] += "<p>WebSocket
connection opened.</p>";

const permission = await


requestNotificationPermission();
if (permission === 'granted') {
sendNotification('WebSocket Connected', {
body: 'You are now connected to the Weather
WebSocket server.',
icon: 'path/to/[Link]' // Replace with the path to
your icon
});
}
});
[Link]('message', (event) => {
[Link]('Weather update from server:', [Link]);
const weatherData = [Link]([Link]); // Assume
server sends JSON data
displayWeatherUpdate(weatherData);

if ([Link] === 'Rain') {


sendNotification('Weather Alert', {
body: 'It is starting to rain!',
icon: 'path/to/[Link]' // Replace with the path to
your icon
});
}
});

[Link]('close', (event) => {


[Link]('WebSocket connection closed:', event);
[Link] += "<p>WebSocket
connection closed.</p>";
});

[Link]('error', (event) => {


[Link]('WebSocket error:', event);
[Link] += `<p
class="error">WebSocket error: ${[Link]}</p>`;
});
}

function displayWeatherUpdate(weatherData) {
const weatherUpdatesDiv =
[Link]('weatherUpdates');
[Link] += `
<h2>${[Link]}</h2>
<p>Temperature: ${[Link]}°C</p>
<p>Condition: ${[Link]}</p>
<p>Humidity: ${[Link]}%</p>
<p>Wind Speed: ${[Link]} km/h</p>
`;
}
```

Explanation:
1. HTML Structure: The HTML page contains a button
(`Connect to WebSocket`) and a div (`weatherUpdates`) to
display weather updates from the WebSocket server. Basic
styling is added to improve the appearance.
2. JavaScript Code:
- Notification Permission: The
`requestNotificationPermission` function requests permission
from the user to send notifications.
- Sending Notifications: The `sendNotification` function
sends a notification if permission is granted.
- WebSocket Connection: The `connectWebSocket` function
establishes a WebSocket connection to the weather server.
- Event Listeners: Event listeners handle WebSocket events
(`open`, `message`, `close`, `error`) and display appropriate
notifications.
- Display Weather Updates: The `displayWeatherUpdate`
function updates the HTML with the received weather data
and sends a notification if the weather condition is "Rain".

You might also like