Web API
Last Updated: Apr 13, 2025
Local Storage and Session Storage
The Web Storage API allows storing key-value pairs in the browser.
Local Storage (Persistent Storage)
Data stored using localStorage
persists even after the browser is closed.
Setting and Getting Data
// Store data localStorage.setItem("username", "Alice"); // Retrieve data let user = localStorage.getItem("username"); console.log(user); // Outputs: Alice
Removing Data
localStorage.removeItem("username"); // Removes a specific item localStorage.clear(); // Clears all stored data
Session Storage (Temporary Storage)
Session storage works like local storage but clears data when the session (tab) is closed.
sessionStorage.setItem("sessionUser", "Bob"); console.log(sessionStorage.getItem("sessionUser")); sessionStorage.removeItem("sessionUser");
Fetch API (Making HTTP Requests)
The Fetch API allows JavaScript to make network requests asynchronously, commonly used for retrieving data from APIs.
Fetching Data from an API
fetch("https://jsonplaceholder.typicode.com/users/1") .then(response => response.json()) // Convert response to JSON .then(data => console.log(data)) // Handle retrieved data .catch(error => console.error("Error:", error)); // Handle errors
Using async/await
for Fetch Requests
async function getUserData() { try { let response = await fetch("https://jsonplaceholder.typicode.com/users/1"); let data = await response.json(); console.log(data); } catch (error) { console.log("Error fetching data:", error); } } getUserData();
Sending Data Using POST Request
fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "New Post", body: "Post content", userId: 1 }) }) .then(response => response.json()) .then(data => console.log("Post created:", data)) .catch(error => console.log("Error:", error));
Geolocation API (Getting User Location)
The Geolocation API retrieves the user's current location.
Checking if Geolocation is Supported
if ("geolocation" in navigator) { console.log("Geolocation is supported!"); } else { console.log("Geolocation is not supported."); }
Getting User's Current Location
navigator.geolocation.getCurrentPosition( position => { console.log("Latitude:", position.coords.latitude); console.log("Longitude:", position.coords.longitude); }, error => console.log("Error getting location:", error.message) );
Tracking User Location in Real-Time
navigator.geolocation.watchPosition( position => { console.log("Updated Location:", position.coords.latitude, position.coords.longitude); } );
Clipboard API (Copying and Pasting Data)
The Clipboard API allows copying and pasting text programmatically.
Copying Text to Clipboard
navigator.clipboard.writeText("Copied text!").then(() => { console.log("Text copied to clipboard!"); });
Reading Text from Clipboard
navigator.clipboard.readText().then(text => { console.log("Clipboard content:", text); });
Notification API (Displaying Browser Notifications)
The Notification API allows web applications to send notifications to users.
Requesting Notification Permission
if (Notification.permission !== "granted") { Notification.requestPermission().then(permission => { console.log("Notification permission:", permission); }); }
Sending a Notification
new Notification("Hello!", { body: "This is a notification from JavaScript.", icon: "icon.png" });
Intersection Observer API (Detecting Element Visibility)
The Intersection Observer API detects when an element enters or leaves the viewport, useful for lazy loading images or triggering animations.
let observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { console.log("Element is in view:", entry.target); } }); }); let targetElement = document.getElementById("observe-me"); observer.observe(targetElement);
Conclusion
Web APIs extend JavaScript's capabilities by enabling data storage, making HTTP requests, accessing user location, handling clipboard interactions, and displaying notifications. The next section will explore browser compatibility and performance optimization techniques to ensure smooth execution across different devices and environments.
Web API
Last Updated: Apr 13, 2025
Local Storage and Session Storage
The Web Storage API allows storing key-value pairs in the browser.
Local Storage (Persistent Storage)
Data stored using localStorage
persists even after the browser is closed.
Setting and Getting Data
// Store data localStorage.setItem("username", "Alice"); // Retrieve data let user = localStorage.getItem("username"); console.log(user); // Outputs: Alice
Removing Data
localStorage.removeItem("username"); // Removes a specific item localStorage.clear(); // Clears all stored data
Session Storage (Temporary Storage)
Session storage works like local storage but clears data when the session (tab) is closed.
sessionStorage.setItem("sessionUser", "Bob"); console.log(sessionStorage.getItem("sessionUser")); sessionStorage.removeItem("sessionUser");
Fetch API (Making HTTP Requests)
The Fetch API allows JavaScript to make network requests asynchronously, commonly used for retrieving data from APIs.
Fetching Data from an API
fetch("https://jsonplaceholder.typicode.com/users/1") .then(response => response.json()) // Convert response to JSON .then(data => console.log(data)) // Handle retrieved data .catch(error => console.error("Error:", error)); // Handle errors
Using async/await
for Fetch Requests
async function getUserData() { try { let response = await fetch("https://jsonplaceholder.typicode.com/users/1"); let data = await response.json(); console.log(data); } catch (error) { console.log("Error fetching data:", error); } } getUserData();
Sending Data Using POST Request
fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "New Post", body: "Post content", userId: 1 }) }) .then(response => response.json()) .then(data => console.log("Post created:", data)) .catch(error => console.log("Error:", error));
Geolocation API (Getting User Location)
The Geolocation API retrieves the user's current location.
Checking if Geolocation is Supported
if ("geolocation" in navigator) { console.log("Geolocation is supported!"); } else { console.log("Geolocation is not supported."); }
Getting User's Current Location
navigator.geolocation.getCurrentPosition( position => { console.log("Latitude:", position.coords.latitude); console.log("Longitude:", position.coords.longitude); }, error => console.log("Error getting location:", error.message) );
Tracking User Location in Real-Time
navigator.geolocation.watchPosition( position => { console.log("Updated Location:", position.coords.latitude, position.coords.longitude); } );
Clipboard API (Copying and Pasting Data)
The Clipboard API allows copying and pasting text programmatically.
Copying Text to Clipboard
navigator.clipboard.writeText("Copied text!").then(() => { console.log("Text copied to clipboard!"); });
Reading Text from Clipboard
navigator.clipboard.readText().then(text => { console.log("Clipboard content:", text); });
Notification API (Displaying Browser Notifications)
The Notification API allows web applications to send notifications to users.
Requesting Notification Permission
if (Notification.permission !== "granted") { Notification.requestPermission().then(permission => { console.log("Notification permission:", permission); }); }
Sending a Notification
new Notification("Hello!", { body: "This is a notification from JavaScript.", icon: "icon.png" });
Intersection Observer API (Detecting Element Visibility)
The Intersection Observer API detects when an element enters or leaves the viewport, useful for lazy loading images or triggering animations.
let observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { console.log("Element is in view:", entry.target); } }); }); let targetElement = document.getElementById("observe-me"); observer.observe(targetElement);
Conclusion
Web APIs extend JavaScript's capabilities by enabling data storage, making HTTP requests, accessing user location, handling clipboard interactions, and displaying notifications. The next section will explore browser compatibility and performance optimization techniques to ensure smooth execution across different devices and environments.
Web API
Last Updated: Apr 13, 2025
Local Storage and Session Storage
The Web Storage API allows storing key-value pairs in the browser.
Local Storage (Persistent Storage)
Data stored using localStorage
persists even after the browser is closed.
Setting and Getting Data
// Store data localStorage.setItem("username", "Alice"); // Retrieve data let user = localStorage.getItem("username"); console.log(user); // Outputs: Alice
Removing Data
localStorage.removeItem("username"); // Removes a specific item localStorage.clear(); // Clears all stored data
Session Storage (Temporary Storage)
Session storage works like local storage but clears data when the session (tab) is closed.
sessionStorage.setItem("sessionUser", "Bob"); console.log(sessionStorage.getItem("sessionUser")); sessionStorage.removeItem("sessionUser");
Fetch API (Making HTTP Requests)
The Fetch API allows JavaScript to make network requests asynchronously, commonly used for retrieving data from APIs.
Fetching Data from an API
fetch("https://jsonplaceholder.typicode.com/users/1") .then(response => response.json()) // Convert response to JSON .then(data => console.log(data)) // Handle retrieved data .catch(error => console.error("Error:", error)); // Handle errors
Using async/await
for Fetch Requests
async function getUserData() { try { let response = await fetch("https://jsonplaceholder.typicode.com/users/1"); let data = await response.json(); console.log(data); } catch (error) { console.log("Error fetching data:", error); } } getUserData();
Sending Data Using POST Request
fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "New Post", body: "Post content", userId: 1 }) }) .then(response => response.json()) .then(data => console.log("Post created:", data)) .catch(error => console.log("Error:", error));
Geolocation API (Getting User Location)
The Geolocation API retrieves the user's current location.
Checking if Geolocation is Supported
if ("geolocation" in navigator) { console.log("Geolocation is supported!"); } else { console.log("Geolocation is not supported."); }
Getting User's Current Location
navigator.geolocation.getCurrentPosition( position => { console.log("Latitude:", position.coords.latitude); console.log("Longitude:", position.coords.longitude); }, error => console.log("Error getting location:", error.message) );
Tracking User Location in Real-Time
navigator.geolocation.watchPosition( position => { console.log("Updated Location:", position.coords.latitude, position.coords.longitude); } );
Clipboard API (Copying and Pasting Data)
The Clipboard API allows copying and pasting text programmatically.
Copying Text to Clipboard
navigator.clipboard.writeText("Copied text!").then(() => { console.log("Text copied to clipboard!"); });
Reading Text from Clipboard
navigator.clipboard.readText().then(text => { console.log("Clipboard content:", text); });
Notification API (Displaying Browser Notifications)
The Notification API allows web applications to send notifications to users.
Requesting Notification Permission
if (Notification.permission !== "granted") { Notification.requestPermission().then(permission => { console.log("Notification permission:", permission); }); }
Sending a Notification
new Notification("Hello!", { body: "This is a notification from JavaScript.", icon: "icon.png" });
Intersection Observer API (Detecting Element Visibility)
The Intersection Observer API detects when an element enters or leaves the viewport, useful for lazy loading images or triggering animations.
let observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { console.log("Element is in view:", entry.target); } }); }); let targetElement = document.getElementById("observe-me"); observer.observe(targetElement);
Conclusion
Web APIs extend JavaScript's capabilities by enabling data storage, making HTTP requests, accessing user location, handling clipboard interactions, and displaying notifications. The next section will explore browser compatibility and performance optimization techniques to ensure smooth execution across different devices and environments.
ECOSYSTEMS
FOLLOW US
Copyright ©2025. Open Ecosystems
ECOSYSTEMS
FOLLOW US
Copyright ©2025. Open Ecosystems
ECOSYSTEMS
FOLLOW US
Copyright ©2025. Open Ecosystems