JavaScript: Browser APIs & BOM
Explore the Browser Object Model, window, location, navigator, history, and storage APIs built into every browser.
What is the BOM?
The Browser Object Model (BOM) is a collection of objects the browser exposes to JavaScript. Unlike the DOM (which models the page content), the BOM gives access to the browser environment itself: the window, the URL, navigation history, and device information.
Browser Object Model
The BOM is not a formal standard, it is a set of APIs implemented by all major browsers that let JS interact with the browser outside of the document.
- window: the global object; all global variables and functions live here
- location: current URL and navigation methods
- navigator: browser and device information
- history: the browser session history
- screen: screen dimensions
The Window Object
window is the top-level global object in a browser environment.
Press Run to execute the code and see output here.
alert(), confirm(), prompt()
These three methods open native browser dialog boxes. They block execution until the user responds, so they are simple but disruptive, avoid them in production UIs.
Browser Dialogs
Native dialogs are synchronous and pause all JavaScript execution until dismissed. Useful for quick debugging, but use custom modals in real apps.
- alert(msg): shows a message; user can only click OK
- confirm(msg): returns true (OK) or false (Cancel)
- prompt(msg, default): returns the string the user typed, or null
Dialog Return Values
confirm() returns a boolean; prompt() returns a string or null.
Press Run to execute the code and see output here.
setTimeout() and setInterval()
Timers let you schedule code to run after a delay or repeatedly at an interval. Both return an ID you can pass to their clear counterpart to cancel.
Timers
Timers are asynchronous, they do not block the rest of your code while waiting.
- setTimeout(fn, ms): run fn once after ms milliseconds
- setInterval(fn, ms): run fn every ms milliseconds
- clearTimeout(id): cancel a pending setTimeout
- clearInterval(id): stop a running setInterval
setTimeout and setInterval
Schedule delayed and repeated code execution.
Press Run to execute the code and see output here.
open(), close(), scrollTo(), scrollBy()
The window object provides methods for opening new browser tabs, closing them, and programmatically scrolling the page.
Window Navigation Methods
These methods control the browser window and scroll position from JavaScript.
- window.open(url, target): open a URL in a new tab or window
- window.close(): close the current window (only works if opened by script)
- window.scrollTo(x, y): scroll to an absolute position
- window.scrollBy(x, y): scroll by a relative amount
- Pass { top, left, behavior: 'smooth' } for smooth scrolling
Scroll and Open
Programmatic scrolling using scrollTo and scrollBy.
Press Run to execute the code and see output here.
The Location Object
window.location (or just location) represents the current URL and lets you read its parts or navigate to a new address.
window.location
location exposes the current URL as individual readable properties and provides methods to navigate or reload.
- location.href: full URL string; assign to navigate
- location.hostname: domain name only (e.g. "example.com")
- location.pathname: path after the domain (e.g. "/about")
- location.search: query string (e.g. "?id=5")
- location.reload(): reload the current page
- location.replace(url): navigate without adding to history
Location Properties
Break down the current URL into its parts.
Press Run to execute the code and see output here.
The Navigator Object
navigator provides information about the browser and the device running it, including the user agent string and geolocation API.
window.navigator
navigator exposes browser identity, language, online status, and access to device APIs like geolocation.
- navigator.userAgent: browser and OS identification string
- navigator.platform: OS platform (deprecated, but still widely used)
- navigator.language: user's preferred language (e.g. "en-US")
- navigator.onLine: true if the browser has network access
- navigator.geolocation: API to request the user's location
Navigator Properties
Read browser and device information from navigator.
Press Run to execute the code and see output here.
The History Object
history represents the browser's session history. You can navigate back and forward, and with pushState you can change the URL without a page reload (the foundation of SPA routing).
window.history
history lets you move through visited pages and manipulate the URL bar without triggering a full page load.
- history.back(): equivalent to clicking the browser Back button
- history.forward(): equivalent to clicking Forward
- history.go(n): go n steps (negative for back, positive for forward)
- history.pushState(state, title, url): add a new entry and update the URL
- history.replaceState(state, title, url): update URL without adding an entry
History API
Navigate history and update the URL without a page reload.
Press Run to execute the code and see output here.
localStorage
localStorage stores key-value pairs in the browser with no expiry date. The data persists even after the tab or browser is closed.
localStorage
localStorage stores strings persistently. Use JSON.stringify/parse to store objects or arrays.
- localStorage.setItem(key, value): store a value
- localStorage.getItem(key): retrieve a value (returns null if missing)
- localStorage.removeItem(key): delete one key
- localStorage.clear(): delete all keys for this origin
- Values must be strings; wrap objects with JSON.stringify / JSON.parse
localStorage Example
Save, read, and remove items from localStorage.
Press Run to execute the code and see output here.
sessionStorage
sessionStorage works the same as localStorage but data is cleared when the tab is closed. It is scoped to the tab, so two tabs do not share the same sessionStorage.
sessionStorage vs localStorage
Both use the same API. The only difference is lifetime and scope.
- localStorage: persists across sessions, shared across tabs of the same origin
- sessionStorage: cleared when the tab closes, isolated per tab
- Use sessionStorage for temporary state (e.g. wizard step, form draft)
- Use localStorage for persistent preferences (e.g. theme, auth token)
sessionStorage Example
Temporary storage cleared when the browser tab closes.
Press Run to execute the code and see output here.
Cookies
Cookies are small pieces of data stored by the browser and sent with every HTTP request to the server. They are older than localStorage and have more configuration options (expiry, domain, path, secure flag).
document.cookie
Cookies are primarily used for server communication (sessions, authentication). For client-only storage, prefer localStorage or sessionStorage.
- Set a cookie: document.cookie = "key=value; expires=...; path=/"
- Reading document.cookie returns ALL cookies as one string
- max-age=seconds: alternative to expires (preferred)
- HttpOnly: server-set flag; JS cannot read the cookie (security)
- Cookies are sent to the server on every request to the matching domain/path
Cookie Basics
Set, read, and delete cookies using document.cookie.
Press Run to execute the code and see output here.
Knowledge Check
1. Which method shows a dialog box with OK and Cancel buttons?
2. Which property of the location object contains the full URL?
3. Where is localStorage data stored?
4. Which method saves a key-value pair in localStorage?
5. What does navigator.userAgent return?
6. Which history method navigates to the previous page?
7. What does clearTimeout() do?
8. Which method converts a JavaScript object to a JSON string?