Skip to main content

8. Browser & Web APIs

The browser provides powerful APIs that let you interact with the environment, store data, and communicate with servers. Understanding these APIs unlocks advanced web features.


8.1 Browser Object Model (BOM)

window

The global object for everything in the browser.

console.log(window.innerWidth, window.innerHeight);

Gives info about the browser and device.

console.log(navigator.userAgent);

history

Manipulate browser history.

history.back();
history.forward();

location

Get or set the URL.

console.log(location.href);
// location.href = 'https://example.com';

document

The DOM root. See the DOM section for details.


8.2 Storage

Local Storage

Stores data with no expiration.

localStorage.setItem('theme', 'dark');
let theme = localStorage.getItem('theme');

Session Storage

Cleared when the tab closes.

sessionStorage.setItem('user', 'Sam');

Cookies

Small pieces of data sent to the server.

document.cookie = 'token=abc; path=/;';

8.3 Fetch API

Modern way to make HTTP requests.

fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));

Tip: Use async/await for cleaner code:

async function getData() {
try {
let res = await fetch('https://api.example.com/data');
let data = await res.json();
console.log(data);
} catch (e) {
console.error(e);
}
}

Next: OOPS in JavaScript