learn2kode.in

HTML APIs

HTML APIs allow web pages to interact with the browser, device, and system features using JavaScript. These APIs are built into modern browsers and enable powerful functionality such as storing data, drawing graphics, detecting location, and more.

HTML alone cannot perform these actions — but when combined with JavaScript, HTML APIs make websites dynamic and interactive.

Commonly Used HTML APIs

Below is a table of popular browser APIs and their purposes:

API Name Purpose Example Use
Geolocation API Get user's location (latitude & longitude) navigator.geolocation.getCurrentPosition()
Canvas API Draw shapes, graphics, animations Using canvas.getContext("2d")
Web Storage API Store data in browser: localStorage / sessionStorage localStorage.setItem("name","John")
Fetch API Send HTTP requests (modern AJAX) fetch("data.json")
Drag and Drop API Enable dragging elements on the page draggable="true"
Web Workers API Run JavaScript in background threads new Worker("worker.js")
Web Speech API Speech recognition and speech synthesis new SpeechSynthesisUtterance()
Clipboard API Copy & paste text programmatically navigator.clipboard.writeText()
Fullscreen API Make elements enter fullscreen mode element.requestFullscreen()

1. Geolocation API Example

<!DOCTYPE html>
<html>
<body>

<h3>Get User Location</h3>

<button onclick="getLocation()">Show My Location</button>

<p id="output"></p>

<script>
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    document.getElementById("output").innerHTML =
    "Geolocation is not supported by your browser.";
  }
}

function showPosition(position) {
  document.getElementById("output").innerHTML =
    "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

Get User Location

2. Web Storage API Example

<!DOCTYPE html>
<html>
<body>

<h3>Local Storage Example</h3>

<button onclick="save()">Save Name</button>
<button onclick="load()">Load Name</button>

<p id="result"></p>

<script>
function save() {
  localStorage.setItem("username", "John Doe");
}

function load() {
  document.getElementById("result").innerHTML =
    localStorage.getItem("username");
}
</script>

</body>
</html>

Local Storage Example

3. Canvas API Example

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000"></canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 100);
</script>

</body>
</html>

4. Fetch API Example

<script>
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(data => console.log(data));
</script>