Web API
Web APIs (Application Programming Interfaces) provide built-in functionalities that allow JavaScript to interact with the browser and external services. This section covers key browser APIs, including LocalStorage, SessionStorage, Fetch API, and Geolocation API.
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
localStorage.setItem("username", "Alice");
let user = localStorage.getItem("username");
console.log(user);
Removing Data
localStorage.removeItem("username");
localStorage.clear();
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())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
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.