W03 Learning Activity: Native Browser Web APIs
Overview
At this point, in your own development, you hopefully have realized that developers do not need to write everything themselves and you have already used Web APIs that are native (built-in) to the browser in your work. There are many native APIs and even more interfaces (object types) available to be used in web development.
You have already used the DOM, Fetch, and localStorage APIs in your web development journey.
This learning activity focuses on some of those Web APIs supported in modern browsers and in the Node.js runtime.
Prepare
Storage API (session)
The sessionStorage
API is great for temporary data like storing form progress during a single user
session, keeping track of which tab is active, and holding flags just while the tab is open. It does not require a
database nor the use of cookies.
It is only available during an active session and is cleared when the tab is closed, thus making it a bit more
secure than localStorage
given that localStorage data persists even after the browser is closed.
Data in sessionStorage
is not completely secure and should not be used to store sensitive
information.
To set a session storage item, use this general form where key is the identifier and value is the data you want to store:
sessionStorage.setItem('key', 'value');
To retrieve a session storage item, use this general form:
sessionStorage.getItem('key');
To remove a session storage item, use:
sessionStorage.removeItem('key');
To clear all session storage items, use:
sessionStorage.clear();
To check if a session storage item exists, use this general form:
if (sessionStorage.getItem('key') !== null) {
// item exists
}
The following CodePen sessionStorage provides an example of using sessionStorage.
Validation API
The Validation API is a built-in browser API that allows you to respond to the validation of user input in HTML
forms. It provides a way to check if the attributes set in the HTML input
are met. Such things such
as being required
, having a specific format, or being within a certain range, for example using
min
and max
.
To use the Validation API, you can use the checkValidity()
method on an input element. This method
returns a boolean value indicating whether the input is valid or not. If the input is invalid, you can use the
setCustomValidity()
method to set a custom error message.
To check if an input is valid, use this general form:
if (inputElement.checkValidity()) {
// input is valid
} else {
// input is invalid
inputElement.setCustomValidity('Custom error message');
}
The variable, inputElement
, refers to the referenced input element you want to validate.
The following CodePen Validation API
uses the checkValidity()
method to check a user input pattern requirement.
Geolocation API
The Geolocation API is a built-in browser API that allows you to access the user's geographical location. It provides a way to get the user's current position in latitude and longitude, watch for changes in position, and handle errors that may occur while trying to access the location.
To use the Geolocation API, you can use the navigator.geolocation
object. This object provides
methods to get the user's current position and watch for changes in position.
To get the user's current position, use this general form:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
The variable, successCallback
, is a function that is called when the position is successfully
retrieved. The variable, errorCallback
, is a function that is called when there is an error
retrieving the position.
To watch for changes in position, use this general form:
navigator.geolocation.watchPosition(successCallback, errorCallback);
The following example uses getCurrentPosition()
method to get your position in latitude and longitude
and determine a geographic region of the world.
See example Code
const button = document.querySelector("#location-button");
const location = document.querySelector(".location");
button.addEventListener("click", function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// output
location.innerHTML = `Latitude: ${latitude} 🧠Longitude: ${longitude}`;
location.innerHTML += `
Region: ${getRegion(latitude, longitude)}`;
},
function (error) {
location.textContent = `Error: ${error.message}`;
}
);
} else {
location.textContent = "Geolocation is not supported by this browser.";
}
});
function getRegion(lat, lon) {
if (lon > 180) lon -= 360; //normalize to -180..180
switch (true) {
// North America (excl. Mexico/Central America)
case lat >= 24 && lat <= 83 && lon >= -172 && lon <= -52:
return "North America" ;
// Mexico and Central America
case lat >= 7 && lat < 24 && lon >= -118 && lon <= -77:
return "Mexico and Central America";
// South America
case lat >= -56 && lat <= 13 && lon >= -82 && lon <= -34:
return "South America";
// Europe
case lat>= 35 && lat <= 71 && lon >= -25 && lon <= 45:
return "Europe";
// Africa
case lat >= -35 && lat <= 37 && lon >= -17 && lon <= 52:
return "Africa";
// Asia
case lat >= 5 && lat <= 80 && lon >= 45 && lon <= 180:
return "Asia";
// Oceania
case lat >= -50 && lat <= 0 && lon >= 110 && lon <= 180:
return "Oceania";
default:
return "Not mapped";
}
}
Your browser will prompt you for permission to allow this page to discover your location.
Optional Resources
- Complete list of Web APIs – MDN
- Using Web APIs – MDN
- Validation API – MDN
- Using JavaScript Validation – MDN
- Geolocation API – MDN
- Session Storage API – MDN
- Canvas API Tutorial – MDN