- Published on
Browser APIs
Browser APIs in JavaScript provide functionalities like storing data locally, making HTTP requests, managing browsing history, and accessing device location, enhancing web applications with interactive features and improved user experiences.
Table of Contents
Local Storage
- Local Storage is a mechanism provided by web browsers that allows web applications to
store data locallywithin the user's browser. - It provides a simple
key-value storage systemwhere data ispersistedeven after the browser window is closed or the user navigates away from the page. - It's commonly used for storing small amounts of data such as
user preferences,sessioninformation, orcached datato improve application performance. - Data stored in local storage is
scoped to the origin(the combination of protocol, domain, and port), meaning data from one origin cannot be accessed by another. - To use local storage, you can access the
localStorageobject in JavaScript. - To store data, use
localStorage.setItem(key, value). - To retrieve data, use
localStorage.getItem(key). - To remove data, use
localStorage.removeItem(key).
Example:
localStorage.setItem('username', 'rajnish')
let username = localStorage.getItem('username')
console.log(username) // Output: rajnish
Fetch API
- The Fetch API provides an interface for making HTTP requests in the browser, allowing web developers to fetch resources asynchronously from the server.
- It provides a more powerful and flexible alternative to the older
XMLHttpRequest (XHR) API. - Fetch API supports
promises, making it easier to work withasynchronouscode and providing a cleaner syntax compared to callbacks. - It supports various features such as
streaming responses,sending and receiving JSON data,setting request headers, andhandling different types of content. - To make an HTTP request using Fetch API, use the
fetch()function. - Pass the URL of the resource you want to fetch as an argument to
fetch(). - Handle the promise returned by
fetch()using.then()and.catch()to process the response or handle errors.
Example:
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error))
History API
- The History API allows developers to interact with the browser's
session history, enabling them tomanipulate the browser's history stackand navigate programmatically between different states of a web application. - It provides methods to
add,modify, orreplaceentries in the browser's history without causing a full page refresh. - With the History API, developers can create seamless
user experiencesby implementing features such as client-side routing, dynamic content loading, and browser navigation controls. - It consists of methods like
pushState(),replaceState(), and events likepopstate, which enable developers to manage browser history in response to user actions or application events. - To manipulate browser history, use methods like
pushState(),replaceState(), and listen for thepopstate event. - Use
history.pushState(state, title, url)to add a new entry to the history stack. - Use
history.replaceState(state, title, url)to modify the current entry in the history stack. - Listen for the
popstateevent to handle browser navigation changes.
Example:
history.pushState({ page: 1 }, 'Title', '/page1')
window.onpopstate = function (event) {
console.log('Location: ' + document.location + ', State: ' + JSON.stringify(event.state))
}
Geolocation API
- The Geolocation API allows web applications to retrieve the
user's geographical location information, such as latitude and longitude coordinates, using the device's built-in location capabilities (like GPS). - It provides a simple interface for obtaining location data
asynchronously, enabling developers to create location-aware web applications. - Geolocation API respects
user privacyand requires explicit user consent before accessing location information. - Developers can use
location datato customize content based on the user's location, provide location-based services, or display maps and directions within the application. - To get the user's location, use the
navigator.geolocationobject. - Call
navigator.geolocation.getCurrentPosition()to retrieve the user's current position. - Handle the position data returned
asynchronouslyin a callback function.
Example:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
console.log(
'Latitude: ' + position.coords.latitude + ', Longitude: ' + position.coords.longitude
)
},
function (error) {
console.error('Error getting location:', error)
}
)
} else {
console.error('Geolocation is not supported.')
}