Web APIs are interfaces provided by the browser that let JavaScript interact with the page, the device, and the network. This chapter surveys the most commonly used browser APIs and introduces JSON and jQuery.
Modern browsers ship dozens of APIs. Here are the most important ones for everyday development:
Access the user’s current geographic location (with permission).
navigator.geolocation.getCurrentPosition(pos => {
console.log(`Lat: ${pos.coords.latitude}, Lng: ${pos.coords.longitude}`);
}, err => {
console.error('Location denied:', err.message);
});
localStorage persists data across browser sessions; sessionStorage clears when the tab closes. Both store key-value pairs as strings.
// Save
localStorage.setItem('theme', 'dark');
// Read
const theme = localStorage.getItem('theme');
// Remove
localStorage.removeItem('theme');
// Clear all
localStorage.clear();
Manipulate the browser’s session history without triggering a full page reload — essential for single-page applications.
// Push a new state
history.pushState({ page: 1 }, 'Page 1', '/page1');
// Listen for back/forward
window.addEventListener('popstate', e => {
console.log('State:', e.state);
});
Make HTTP requests from the browser. It returns a Promise that resolves to the Response object.
fetch('https://api.example.com/data')
.then(res => { if (!res.ok) throw new Error('Network error'); return res.json(); })
.then(data => console.log(data))
.catch(err => console.error(err));
Draw 2D graphics programmatically. The <canvas> element provides a drawing surface.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 60);
Run JavaScript in a background thread, keeping the UI thread responsive.
// main.js
const worker = new Worker('worker.js');
worker.postMessage('Hello from main');
worker.onmessage = e => console.log('Worker says:', e.data);
// worker.js
onmessage = e => { postMessage('Hello back!'); };
AJAX (Asynchronous JavaScript and XML) lets web pages send and receive data from a server without refreshing. The modern approach uses the Fetch API; the older approach uses XMLHttpRequest.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = () => { console.log(JSON.parse(xhr.responseText)); };
xhr.send();
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is language-independent but uses conventions familiar to JavaScript developers.
{
"name": "Alice",
"age": 30,
"skills": ["JavaScript", "Python"],
"active": true
}
const jsonStr = '{"name":"Bob","age":25}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // Bob
const backToJson = JSON.stringify(obj);
console.log(backToJson); // {"name":"Bob","age":25}
jQuery is a fast, small library that simplifies HTML document traversal, event handling, and animation. While modern frameworks have reduced its necessity, many legacy projects still use it.
// jQuery selectors (using $ alias)
$('.my-class').hide();
$('#my-id').css('color', 'red');
$('p:first').text('First paragraph');
$('button').click(() => alert('Clicked!'));
$('form').on('submit', e => {
e.preventDefault();
console.log('Form submitted');
});
$.ajax({
url: '/api/data',
method: 'GET',
success: data => console.log(data),
error: (xhr, status, err) => console.error(err)
});
Build a page with a button that toggles between light and dark themes. Store the user’s preference in localStorage so the theme persists across page reloads. Use the Geolocation API to display the user’s approximate latitude and longitude below the theme toggle.