Javascript | Web APIs
--
Summary,
- Web Geolocation API — window.navigator.geolocation.getCurrentPosition(callback)
- Web History API — window.history
- Web Storage API — window.localStorage, window.sessionStorage
- Web Workers API — new Worker(), postMessage(), new Worker().message (callback)[event listener]
- Web Fetch API — fetch().then()
- Web Drag and Drop API- e.dataTransfer.setData(‘text/plain’, e.target.id), e.dataTransfer.getData
- Web Notification API- new Notification(….), window.notification.permission
Geolocation API
- navigator.geolocation.getCurrentPosition(callbackSuccess, callbackError, options)
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
const crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
body {
font-family: 'Arial', sans-serif;
text-align: center;
margin: 20px;
}
#location-info {
font-size: 18px;
margin-top: 20px;
}
</style>
<title>Geolocation API Example</title>
</head>
<body>
<h1>Geolocation API Example</h1>
<button onclick="getLocation()">Get Location</button>
<div id="location-info"></div>
<script>
function getLocation() {
// Check if Geolocation is supported
if (navigator.geolocation) {
// Call getCurrentPosition with success and error callbacks
navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback
);
} else {
document.getElementById('location-info').innerHTML =
'Geolocation is not supported by this browser.';
}
}
function successCallback(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// Display the location information
const locationInfo = `Latitude: ${latitude}<br>Longitude: ${longitude}`;
document.getElementById('location-info').innerHTML = locationInfo;
}
function errorCallback(error) {
let errorMessage = 'Error getting location: ';
switch (error.code) {
case error.PERMISSION_DENIED:
errorMessage += 'User denied the request for Geolocation.';
break;
case error.POSITION_UNAVAILABLE:
errorMessage += 'Location information is unavailable.';
break;
case error.TIMEOUT:
errorMessage += 'The request to get user location timed out.';
break;
case error.UNKNOWN_ERROR:
errorMessage += 'An unknown error occurred.';
break;
}
document.getElementById('location-info').innerHTML = errorMessage;
}
</script>
</body>
</html>
Web History API,
- window.history.back();
- window.history.go(-2);
- window.history.forward();
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: 'Arial', sans-serif;
text-align: center;
margin: 20px;
}
button {
font-size: 16px;
margin: 5px;
}
#history-info {
font-size: 18px;
margin-top: 20px;
}
</style>
<title>History API Example</title>
</head>
<body>
<h1>History API Example</h1>
<button onclick="goBack()">Go Back</button>
<button onclick="goBackTwo()">Go Back (2 steps)</button>
<button onclick="goForward()">Go Forward</button>
<div id="history-info"></div>
<script>
function goBack() {
window.history.back();
displayHistoryInfo();
}
function goBackTwo() {
window.history.go(-2);
displayHistoryInfo();
}
function goForward() {
window.history.forward();
displayHistoryInfo();
}
function displayHistoryInfo() {
const historyInfo = `Current URL: ${window.location.href}<br>History Length: ${window.history.length}`;
document.getElementById('history-info').innerHTML = historyInfo;
}
</script>
</body>
</html>
Web Storage API
The Web Storage API is a simple syntax for storing and retrieving data in the browser.
window.localStorage,
localStorage.setItem(“name”, “John Doe”);
localStorage.getItem(“name”);
localStorage.removeItem(key);
localStorage.clear();
window.sessionStorage,
sessionStorage.getItem(“name”);
sessionStorage.setItem(“name”, “John Doe”);
Web Workers API
- A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.
- Web worker runs in the background
- Web workers are in external files, they do not have access to the following JavaScript objects: The window object, The document object, The parent object
Create a Web Worker File
postMessage()
method - which is used to post a message back to the HTML page.
let i = 0;
function timedCount() {
i ++;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
Create a Web Worker Object
new Worker("demo_workers.js")
- If the worker already exists, if not — it creates a new web worker object and runs the code
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
Then we can send and receive messages from the web worker.
Add an “onmessage” event listener to the web worker.
w.onmessage = function(event){
document.getElementById(“result”).innerHTML = event.data;
};
Terminate a Web Worker
- w.terminate();
Example,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Workers Example</title>
</head>
<body>
<h1>Web Workers Example</h1>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<div id="result"></div>
<script>
// Function to start the web worker
function startWorker() {
if (typeof(Worker) !== 'undefined') {
// Check if Web Workers are supported
if (typeof(w) == 'undefined') {
// If the worker doesn't exist, create a new one
w = new Worker('worker.js');
// Listen for messages from the worker
w.onmessage = function(event) {
document.getElementById('result').innerHTML = 'Result from Worker: ' + event.data;
};
} else {
document.getElementById('result').innerHTML = 'Worker is already running.';
}
} else {
document.getElementById('result').innerHTML = 'Web Workers are not supported in this browser.';
}
}
// Function to stop the web worker
function stopWorker() {
if (typeof(w) !== 'undefined') {
w.terminate(); // Terminate the worker
w = undefined; // Reset the worker variable
document.getElementById('result').innerHTML = 'Worker stopped.';
} else {
document.getElementById('result').innerHTML = 'No worker to stop.';
}
}
</script>
</body>
</html>
JavaScript Worker File (worker.js
):
// This is the code for the worker
// Listen for messages from the main thread
self.onmessage = function(event) {
// Perform some time-consuming task
const result = 'Result of processing: ' + event.data;
// Send the result back to the main thread
self.postMessage(result);
};
Drag and Drop API,
- HTML5 spec specifies that almost all elements can be draggable.
- To make an element draggable, you add the
draggable
property with the value oftrue
to its HTML tag<div class="item" draggable="true"></div>
/* draggable element */const item = document.querySelector('.item');item.addEventListener('dragstart', dragStart);function dragStart(e) { e.dataTransfer.setData('text/plain', e.target.id); setTimeout(() => { e.target.classList.add('hide'); }, 0);}/* drop targets */const boxes = document.querySelectorAll('.box');boxes.forEach(box => { box.addEventListener('dragenter', dragEnter) box.addEventListener('dragover', dragOver); box.addEventListener('dragleave', dragLeave); box.addEventListener('drop', drop);});function dragEnter(e) { e.preventDefault(); e.target.classList.add('drag-over');}function dragOver(e) { e.preventDefault(); e.target.classList.add('drag-over');}function dragLeave(e) {
e.target.classList.remove('drag-over');
}function drop(e) {
e.target.classList.remove('drag-over'); // get the draggable element const id = e.dataTransfer.getData('text/plain'); const draggable = document.getElementById(id);
// add it to the drop target
e.target.appendChild(draggable); // display the draggable element
draggable.classList.remove('hide');}
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Drag and Drop Example</title>
<style>
.drop-container {
display: flex;
justify-content: space-around;
margin: 20px;
}
.drag-container,
.drop-box {
width: 150px;
height: 150px;
border: 2px dashed #ccc;
padding: 10px;
}
.draggable {
cursor: move;
border: 1px solid #ddd;
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<h1>Drag and Drop Example</h1>
<div class="drop-container">
<div
id="drag-container"
class="drag-container"
ondrop="drop(event)"
ondragover="allowDrop(event)"
>
<div
id="drag1"
class="draggable"
draggable="true"
ondragstart="drag(event)"
>
Drag me!
</div>
<div
id="drag2"
class="draggable"
draggable="true"
ondragstart="drag(event)"
>
Drag me too!
</div>
</div>
<div
id="drop-box"
class="drop-box"
ondrop="drop(event)"
ondragover="allowDrop(event)"
>
Drop Box
</div>
</div>
<script>
// Function to allow dropping
function allowDrop(event) {
event.preventDefault();
}
// Function to start the drag
function drag(event) {
event.dataTransfer.setData('text/plain', event.target.id);
}
// Function to handle the drop
function drop(event) {
event.preventDefault();
const data = event.dataTransfer.getData('text/plain');
const draggedElement = document.getElementById(data);
const dropTarget = event.target;
// Append the dragged element to the drop target
dropTarget.appendChild(draggedElement);
}
</script>
</body>
</html>
Notification API
- Create new Notification,
new Notification('JavaScript Notification API', { body: 'This is a JavaScript Notification API demo', icon: './img/js.png'});
(async () => {// create and show the notificationconst showNotification = () => {// create a new notification const notification = new Notification('Notification API', { body: 'This is a JavaScript Notification API demo', icon: './img/js.png' }); // close the notification after 10 seconds setTimeout(() => { notification.close(); }, 10 * 1000); // navigate to a URL when clicked notification.addEventListener('click', () => { window.open('https://www.javascripttutorial.net/web-apis/javascript-notification/', '_blank'); });}// show an error messageconst showError = () => { const error = document.querySelector('.error'); error.style.display = 'block'; error.textContent = 'You blocked the notifications';}// check notification permissionlet granted = false;if (Notification.permission === 'granted') { granted = true;} else if (Notification.permission !== 'denied') { let permission = await Notification.requestPermission(); granted = permission === 'granted' ? true : false;}// show notification or errorgranted ? showNotification() : showError();})();