
JavaScript Web APIs allow developers to build dynamic and interactive web applications. In this blog I have mentioned 5 JavaScript Web APIs along with examples.
The Fetch API is widely used for interacting with RESTful APIs. It enables developers to retrieve or send data asynchronously.
Example: GET Request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
The DOM API provides methods to select and modify elements in a webpage.
Example: Changing Text Content
const heading = document.querySelector('h1');
heading.textContent = 'Hello, World!';
heading.style.color = 'blue';Local Storage is useful for saving user preferences or application data without relying on a server.
Example: Save and Retrieve Data
// Save the data
localStorage.setItem('theme', 'dark');
// Retrieve data
const theme = localStorage.getItem('theme');
console.log(`Selected theme: ${theme}`);The Geolocation API is used for location-based services like maps or local search results.
Example: Getting the User's Coordinates
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
console.log(`Latitude: ${position.coords.latitude}`);
console.log(`Longitude: ${position.coords.longitude}`);
}, error => {
console.error('Error retrieving location:', error);
});
} else {
console.error('Geolocation not supported.');
}The Notification API lets your app send desktop like notifications.
Example: Sending a Notification
if (Notification.permission === 'granted') {
new Notification('Hello!', { body: 'This is your notification.' });
} else if (Notification.permission !== 'denied') {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
new Notification('Hello!', { body: 'This is your notification.' });
}
});
}
It Enhances user engagement with timely alerts.
Start experimenting with these APIs.
0
7
0