Skip to main content

HTML APIs

HTML5 APIs: Geolocation, Local Storage and Browser Features

HTML5 APIs logos and features

HTML5 introduced powerful APIs that allow web applications to interact with device hardware and browser features.

1. Geolocation API

Get the user's geographical location (with permission):

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    function(position) {
      console.log("Latitude: " + position.coords.latitude);
      console.log("Longitude: " + position.coords.longitude);
    },
    function(error) {
      console.error("Error getting location: " + error.message);
    }
  );
} else {
  console.log("Geolocation is not supported by this browser.");
}

2. Web Storage API (localStorage and sessionStorage)

Difference between localStorage and sessionStorage

localStorage - Persistent storage

// Store data
localStorage.setItem("username", "JohnDoe");

// Retrieve data
const user = localStorage.getItem("username");

// Remove data
localStorage.removeItem("username");

// Clear all
localStorage.clear();

sessionStorage - Temporary storage (cleared when tab closes)

sessionStorage.setItem("theme", "dark");

3. Canvas API

<canvas id="myCanvas" width="200" height="100"></canvas>

<script>
  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d");
  
  // Draw a red rectangle
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(0, 0, 150, 75);
  
  // Draw text
  ctx.font = "30px Arial";
  ctx.fillText("Hello Canvas", 10, 50);
</script>

4. Drag and Drop API

<div id="dropArea" ondrop="drop(event)" ondragover="allowDrop(event)">
  Drop here
</div>

<img id="dragItem" src="image.jpg" draggable="true" 
  ondragstart="drag(event)" width="100" height="100">

<script>
  function allowDrop(e) {
    e.preventDefault();
  }
  
  function drag(e) {
    e.dataTransfer.setData("text", e.target.id);
  }
  
  function drop(e) {
    e.preventDefault();
    const data = e.dataTransfer.getData("text");
    e.target.appendChild(document.getElementById(data));
  }
</script>

5. Web Workers API

Run JavaScript in background threads:

// main.js
const worker = new Worker("worker.js");

worker.postMessage("Start working!");

worker.onmessage = function(e) {
  console.log("Worker says: " + e.data);
};

// worker.js
onmessage = function(e) {
  console.log("Message from main: " + e.data);
  postMessage("Work done!");
};

6. Other HTML5 APIs

  • Web Speech API: Speech recognition and synthesis
  • WebRTC: Real-time communication
  • Web Bluetooth: Interact with Bluetooth devices
  • Payment Request API: Native payment interface

These powerful APIs enable web applications to compete with native apps in functionality and user experience!

Comments