Javascript | Web APIs

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);

Web History API,

  • window.history.back();
  • window.history.go(-2);
  • window.history.forward();

Web Storage API

The Web Storage API is a simple syntax for storing and retrieving data in the browser.

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");
}
w.onmessage = function(event){
document.getElementById(“result”).innerHTML = event.data;
};

Terminate a Web Worker

  • w.terminate();

Example,

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>

<script>
let w;

function startWorker() {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
}

function stopWorker() {
w.terminate();
w = undefined;
}
</script>

</body>
</html>

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 of true 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');
}

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();})();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store