JavaScript Web APIs

Under JavaScript Published at December 14, 2024 Updated at December 14, 2024

#JavaScript Web APIs

JavaScript Web APIs are a set of APIs provided by the browser that allow you to interact with the browser and the document. These APIs are not part of the JavaScript language itself, but are provided by the browser environment.

Some common JavaScript Web APIs include:

#Speech API

// Check if the browser supports the Web Speech API
if ("speechSynthesis" in window) {
  // Create a new SpeechSynthesisUtterance object
  var msg = new SpeechSynthesisUtterance("Hello, world!");

  // Use the speech synthesis API to speak the message
  window.speechSynthesis.speak(msg);
} else {
  console.log("Speech synthesis not supported");
}

In this example, we check if the browser supports the Web Speech API by checking if the speechSynthesis property is available on the window object. If it is, we create a new SpeechSynthesisUtterance object with the message "Hello, world!" and use the speak method of the speechSynthesis object to speak the message.

#Storage API (Local Storage)

// store data in local storage
localStorage.setItem("key", "value");
// retrieve data from local storage
const storedValue = localStorage.getItem("key");
// remove data from local storage
localStorage.removeItem("key");

#Storage API (Session Storage)

// store data in session storage
sessionStorage.setItem("key", "value");
// retrieve data from session storage
const storedValue = sessionStorage.getItem("key");
// remove data from session storage
sessionStorage.removeItem("key");

#Fetch API

// Make a GET request to fetch data from a URL
fetch("https://api.example.com/data")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

#Geolocation API

// Get the user's current location
navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log("Latitude:", position.coords.latitude);
    console.log("Longitude:", position.coords.longitude);
  },
  (error) => {
    console.error(error);
  }
);

#Canvas API

To draw a filled rectangle in blue

// Get the canvas element
const canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
document.body.appendChild(canvas);

// Get the canvas context
const ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 100);

#Audio Api

An oscillator and play a tone

const autoContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();

oscillator.frequency.setValueAtTime(440, audioContext.currentTime);
oscillator.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + 1);

#Websocket Api

Realtime, bidirectional communication between the client and the server

const socket = new WebSocket("wss://echo.websocket.org");
socket.addEventListener("open", () => {
  console.log("Connected to server");
  socket.send("Hello, server!");
});

socket.addEventListener("message", () => {
  console.log("Received message from server:", event.data);
});

socket.addEventListener("close", () => {
  console.log("Connection closed");
});

#IndexedDB Api

// Open a database
const dbName = "my-database";
const dbVersion = 1;

const request = indexedDB.open(dbName, dbVersion);
// handle error that may occur during the database opening process.
request.onerror = (event) => {
  console.error("Database error:", event.target.error);
};
// specify the action to be taken when the database
// structure is
request.onupgradeneeded = (event) => {};

// define the action to be taken upon successful opening of the database.
request.onsuccess = (event) => {};

#File Api

<input type="file" id="file-input" />
const fileInput = document.getElementById("file-input");
fileInput.addEventListener("change", (event) => {
  const file = event.target.files[0];
  console.log("Selected file:", file);
});

#Notification Api

// Request permission to display notifications
Notification.requestPermission().then((permission) => {
  if (permission === "granted") {
    // Display a notification
    new Notification("Hello, world!");
  }
});

#Worker Api

Execute JavaScript code in a separate thread to avoid blocking the main thread and improve performance of the application.

// Create a new worker
const worker = new Worker("worker.js");
worker.postMessage("Hello, worker!");

#Intersection Observer Api

Efficiently observe changes in the visibility of elements on the page.

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      console.log("Element is visible");
    } else {
      console.log("Element is not visible");
    }
  });
});

#Mutation Observer Api

Observe changes to the DOM and react to them.

const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    console.log("Mutation type:", mutation.type);
  });
});
const targetNode = document.getElementById("yourElementId");
const config = { attributes: true, childList: true, subtree: true };
observer.observe(targetNode, config);

#Pointer Lock Api

Captures the mouse pointer precisely in browser.

const element = document.getElementById("yourElementId");
element.requestPointerLock();

#Battery Status Api

Get information about the battery status of the device.

navigator.getBattery().then((battery) => {
  console.log("Battery level:", battery.level * 100 + "%");
  console.log("Charging:", battery.charging ? "Yes" : "No");
});

#Gamepad Api

Interact with gamepads connected to the device.

window.addEventListener("gamepadconnected", (event) => {
  const gamepad = event.gamepad;
  console.log("Gamepad connected:", gamepad.id);
});

window.addEventListener("gamepaddisconnected", (event) => {
  const gamepad = event.gamepad;
  console.log("Gamepad disconnected:", gamepad.id);
});

#DeviceOrientation and Motion Api

Get information about the device's orientation and motion.

window.addEventListener("deviceorientation", (event) => {
  console.log("Alpha:", event.alpha);
  console.log("Beta:", event.beta);
  console.log("Gamma:", event.gamma);
});

window.addEventListener("devicemotion", (event) => {
  console.log("Acceleration X:", event.acceleration.x);
  console.log("Acceleration Y:", event.acceleration.y);
  console.log("Acceleration Z:", event.acceleration.z);
});

#Push Api

Send push notifications to the user.

navigator.serviceWorker.ready.then((registration) => {
  registration.pushManager
    .subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array("yourPublicKey"),
    })
    .then((subscription) => {
      console.log("Push subscription:", subscription);
    });
});

#Payment Request Api

Facilitate streamline online payment processing in the browser.

const supportedInstruments = [
  {
    supportedMethods: "basic-card",
  },
];

const paymentDetails = {
  total: {
    label: "Total",
    amount: {
      currency: "USD",
      value: "10.00",
    },
  },
};

const paymentPromise = new PaymentRequest(supportedInstruments, paymentDetails);

paymentPromise.show().then((paymentResponse) => {
  console.log("Payment response:", paymentResponse);
});

#Web Share Api

Share content with other applications or services.

if (navigator.share) {
  navigator.share({
    title: "Web Share API",
    text: "Check out the Web Share API!",
    url: "https://example.com",
  });
}

Last updated on

December 14, 2024

# of hits