Web APIs

Canvas API

index.html
<canvas id="canvas"></canvas>
index.js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');

ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 150, 100);

DOM

  • DOM document is a big tree of nodes

Fetch API

Geolocation API

  • returns the location of the device

navigator.geolocation.getCurrentPosition(function(loc){
    console.log(loc.coords.latitude + ', ' + loc.coords.longitude);
}

Web Storage API

  • With web storage, web applications can store data locally within the user's browser.

  • Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

  • Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

  • Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

Before using web storage, check browser support for localStorage and sessionStorage:

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support..
}

HTML web storage provides two objects for storing data on the client:

window.localStorage

  • stores the data with no expiration date

index.js
// Store
window.localStorage.setItem("language", "JavaScript");

// Retrieve
console.log(window.localStorage.getItem("language")); // JavaScript

// Delete
window.localStorage.removeItem("language");

sessionStorage

  • stores data for one session (data is lost when the browser tab is closed)

index.js
// Store
sessionStorage.setItem("language", "JavaScript");
// sessionStorage.language = "JavaScript";

// Retrieve
console.log(sessionStorage.getItem("language"));

Name/value pairs are always stored as strings. Remember to convert them to another format when needed.

Web Workers API

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Before creating a web worker, check whether the user's browser supports it:

index.js
if (typeof(Worker) !== "undefined") {
  // Yes! Web worker support!
  // Some code.....
} else {
  // Sorry! No Web Worker support..
}

XHR

XMLHttpRequest (XHR) is a JavaScript API to create AJAX requests.

  • Its methods provide the ability to send network requests between the browser and a server.

  • It can be used to retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.

XMLHttpRequest can be used to retrieve any type of data, not just XML.

Last updated