Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 156 ยท Browser APIs

The Browser Object Model

Explore the Browser Object Model - the window object, navigator, screen and location, alert/confirm/prompt dialogs, opening popups, printing and redirects.

The DOM gives you the page: its elements, text and attributes. But your code also runs inside a browser, with a window of a certain size, a history, an address bar, a screen and a user with language preferences. The collection of objects that describe all of that is informally called the Browser Object Model, or BOM.

Unlike the DOM, the BOM was never one single specification. It grew up as a set of objects every browser offered, and was later written down piece by piece in the HTML standard and other specs. In practice it means a handful of objects hanging off window: navigator, screen, location and history, plus methods for dialogs, popups, timers, scrolling and printing. This lesson tours the parts you'll actually use, and points out the ones better left alone.

window: the global object

In a browser, window is two things at once. It represents the browser window (or tab, or iframe) your code runs in, and it is the global object: global functions and var declarations in classic scripts become its properties, and every built-in global lives on it.

JS window is the global object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can usually leave off the window. prefix: alert() means window.alert(), and innerWidth means window.innerWidth. Use globalThis when you write code that should also run in Node.js or Web Workers, where there is no window.

Because var and function declarations in classic scripts land on the global object, they can clash with each other and with browser properties (try naming a global variable name or status). Modules and let/const avoid that problem.

Window size and scrolling

window also knows about the visible area, called the viewport:

Property Meaning
innerWidth, innerHeight Viewport size in CSS pixels, including any scrollbar
outerWidth, outerHeight The whole browser window, including toolbars
scrollX, scrollY How far the page has scrolled
devicePixelRatio Physical pixels per CSS pixel (2 or 3 on many phones)

document.documentElement.clientWidth gives the viewport width without the scrollbar, which is often what layout code wants. To scroll, call window.scrollTo({ top: 0, behavior: "smooth" }) or scrollBy().

Viewport size and resize

Inside this editor the "window" is the small preview iframe, so innerWidth reports the preview's width, not your browser's. That's true on real sites too: code inside an iframe sees the iframe's viewport.

matchMedia() is often a better choice than reading innerWidth: it uses the exact same syntax as CSS media queries, and its change event fires only when the answer flips, instead of on every pixel of a resize. If you only care about an element's size, use a ResizeObserver.

navigator describes the browser and the user's environment. Some of its most useful properties:

JS What navigator knows

Press Run (or Ctrl + Enter) to see the console output here.

No output.

navigator.language is a good default for Intl formatting or choosing a translation. navigator.onLine together with the online and offline events on window tells you about lost connectivity, though true only means "connected to some network", not that your server is reachable.

navigator is also the home of many modern APIs: navigator.clipboard, navigator.geolocation, navigator.mediaDevices, navigator.share(), navigator.serviceWorker and more. Several of them need a secure (HTTPS) page and user permission, and most are blocked inside this site's sandboxed editors.

Don't sniff the user agent. The userAgent string is full of historical lies ("Mozilla/5.0" in every browser), is being frozen and reduced by browsers for privacy, and is easy to fake. Checking it to decide what code to run breaks constantly. Test for the feature itself instead: if ("share" in navigator) { ... }. For layout decisions, use CSS media queries or matchMedia().

screen: the physical display

screen describes the monitor the window is on:

JavaScript
screen.width, screen.height;          // full screen size in CSS pixels
screen.availWidth, screen.availHeight; // minus taskbars and docks
screen.colorDepth;                     // usually 24
screen.orientation.type;               // "landscape-primary", "portrait-primary", ...

It's rarely needed for layout: the viewport (innerWidth, media queries) is what your page actually gets. screen is mostly useful for positioning popups and for things like choosing video quality.

location and history

window.location holds the current URL and can navigate; window.history moves through the session history. Both are covered in depth in URLs, Location and History. The short version:

JavaScript
location.href;              // the full current address
location.assign("/next");   // go to a new page
location.replace("/login"); // go there, without a Back entry
location.reload();
history.back();

Redirects

To send someone to another page from JavaScript, use location.replace(url) when the current page shouldn't stay in history (otherwise Back bounces the user right back into the redirect), and location.assign(url) or location.href = url when it should.

For permanent moves, prefer a server redirect (HTTP status 301 or 308). It happens before any page loads, works without JavaScript, and tells search engines where the content went. A JavaScript redirect is right for decisions only the browser can make, such as "after the user logs in, go to the dashboard". Never redirect to a URL taken straight from a query parameter without checking it: that's an open redirect, a favorite tool for phishing. The security lesson shows how to check it.

Dialogs: alert, confirm and prompt

The browser has three built-in dialog boxes:

  • alert(message) shows a message with an OK button and returns undefined.
  • confirm(message) shows OK and Cancel, and returns true or false.
  • prompt(message, defaultText) asks for a line of text, and returns the string, or null if the user cancels.

All three are blocking: JavaScript on the page stops until the user answers.

The three built-in dialogs

They're handy for quick experiments and debugging, but avoid them in finished products:

  • They freeze the entire page and can't be styled, so they look different in every browser.
  • Browsers can suppress them: a "prevent this page from creating more dialogs" checkbox, or blocking them in cross-origin iframes and background tabs.
  • prompt() offers no validation, labels or accessible form controls.

For real interfaces, use the HTML <dialog> element, which you can style, fill with a proper form and open with showModal(). It doesn't block your code, so you react to its close event instead of a return value.

Opening new windows

window.open(url, target, features) opens a new tab or a popup window and returns a reference to it (or null if it was blocked):

JavaScript
// A normal new tab (like a link with target="_blank")
window.open("https://example.com/help", "_blank");

// A small popup window: "popup" asks for a minimal window
const popup = window.open("/preview", "preview", "popup,width=480,height=360");

// Safer for third-party pages: the new page can't reach back to yours
window.open("https://partner.example.com", "_blank", "noopener");

Browsers' popup blockers allow window.open() only in direct response to a user action such as a click. Calls from a timer, or long after an await, are usually blocked. Always handle a null result.

Opening and writing to a popup

The opener can control the popup's document here only because an empty (about:blank) window shares the opener's origin. Open a page from another site and the same-origin policy blocks access to its document. To talk across origins, use postMessage.

When a page you open with target="_blank" or window.open() comes from another site, it should not be able to navigate your tab through window.opener. Browsers now treat target="_blank" links as noopener by default, and you should pass "noopener" to window.open() for third-party URLs. window.close() only works on windows your script opened.

Popups annoy many users and behave badly on phones. Prefer a normal link, a new tab or an in-page <dialog>; keep popups for special cases such as sign-in windows from an identity provider.

Printing

window.print() opens the browser's print dialog for the current page, the same as pressing Ctrl+P or Cmd+P. Two events let you adjust the page around it: beforeprint and afterprint.

JavaScript
printButton.addEventListener("click", () => window.print());

window.addEventListener("beforeprint", () => {
  document.querySelectorAll("details").forEach((d) => (d.open = true));
});

Most print styling belongs in CSS, though: an @media print { ... } block can hide navigation, expand links and set page margins without any JavaScript.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does prompt("Your name?") return when the user clicks Cancel?

    prompt() returns the typed text, which can be an empty string, or null when the user cancels.
  2. 2. Why should you avoid checking navigator.userAgent to decide which code to run?

    User agent strings are messy and changing. Feature detection like 'share' in navigator tests what you actually need.
  3. 3. When are window.open() popups most likely to be allowed by the popup blocker?

    Popup blockers let window.open() through when it runs in direct response to a user action such as a click.
  4. 4. A login page should forward users to /dashboard without leaving itself in the history. Which call fits?

    replace() navigates and replaces the current history entry, so Back doesn't return to the login redirect.
  5. 5. Which variable becomes a property of window in a classic (non-module) script?

    Top-level var and function declarations in classic scripts become properties of the global object; let, const and class don't.

Summary

  • The Browser Object Model is the set of objects for the browser itself: window, navigator, screen, location and history.
  • window is the global object; it also reports viewport size and scroll position, and matchMedia() checks media queries from JavaScript.
  • navigator describes language, connectivity and capabilities and hosts many modern APIs; use feature detection, not user agent sniffing.
  • alert(), confirm() and prompt() block the page; use <dialog> in real interfaces.
  • window.open() needs a user gesture and may return null; use noopener for other sites. print() opens the print dialog; redirects use location.replace() or, better, the server.

Next: localStorage and sessionStorage โ€” remembering data in the browser between visits.