Skip to content

js_ex_browser

Interacting with the Browser: BOM Examples

Section titled “Interacting with the Browser: BOM Examples”

The Browser Object Model (BOM) allows JavaScript to interact with the browser, outside the content of the HTML document itself. The BOM is not standardized like the DOM, but most modern browsers implement common BOM features.

The window object represents the browser window or tab. It’s the global object in client-side JavaScript. Many of its properties and methods can be accessed without explicitly writing window..

  • Open a new window: window.open('url', 'windowName', 'features')
  • Control appearance of a new window (via features string in window.open)
  • Focus or blur a window: window.focus(), window.blur()
  • Close a window: window.close() (typically only works for windows opened by script)
  • Check if a window is closed: myWindow.closed (boolean)
  • Interact with parent/opener window (e.g., window.opener)
  • Move a window: window.moveTo(x, y), window.moveBy(dx, dy)
  • Resize a window: window.resizeTo(width, height), window.resizeBy(dw, dh)
  • Print current page: window.print()
  • Scroll content: window.scrollTo(x, y), window.scrollBy(dx, dy)

Learn more about the window object and its extensive capabilities.

The window.screen object contains information about the user’s screen.

  • Screen width: screen.width
  • Screen height: screen.height
  • Available screen width (excluding OS interface like taskbar): screen.availWidth
  • Available screen height: screen.availHeight
  • Color depth: screen.colorDepth (bits per pixel)
  • Pixel depth: screen.pixelDepth (similar to color depth)

This information can be useful for responsive design decisions or analytics, but CSS media queries are generally preferred for styling based on screen characteristics.

The window.location object provides information about the current URL and methods to navigate or reload the page.

  • Full URL: location.href (can also be set to navigate)
  • Protocol: location.protocol (e.g., “http:”, “https:”)
  • Hostname: location.hostname (e.g., “www.example.com”)
  • Port: location.port
  • Pathname: location.pathname (e.g., “/path/to/page.html”)
  • Search string (query parameters): location.search (e.g., “?id=123&category=books”)
  • Hash (fragment identifier): location.hash (e.g., “#section1”)
  • Load a new document: location.assign('new_url') or location.href = 'new_url'
  • Reload the current page: location.reload(forceGet) (true forces reload from server)
  • Replace current document (no history entry): location.replace('new_url')

The URL object (new URL(urlString)) is a more modern and robust way to parse and manipulate URL components.

The window.history object allows interaction with the browser’s session history.

  • Number of URLs in history list: history.length
  • Go back: history.back() (equivalent to browser’s back button)
  • Go forward: history.forward()
  • Go to a specific URL in history: history.go(n) (e.g., history.go(-1) is like back())

Modern single-page applications (SPAs) often use the History API (history.pushState(), history.replaceState(), popstate event) for more sophisticated client-side routing.

The window.navigator object contains information about the browser itself.

  • Cookies enabled: navigator.cookieEnabled (boolean)
  • User agent string: navigator.userAgent (string identifying the browser, use with caution for feature detection)
  • Platform: navigator.platform (e.g., “Win32”, “MacIntel”)
  • Language: navigator.language or navigator.languages (preferred language(s) of the user)
  • Online status: navigator.onLine (boolean, indicates if browser has network connection)
  • Geolocation: navigator.geolocation (provides access to user’s location, requires permission)
  • Clipboard API: navigator.clipboard (for interacting with system clipboard, requires permission)

Best Practice: Instead of browser sniffing (parsing navigator.userAgent), prefer feature detection (checking if a specific object, method, or property exists and works as expected) to determine browser capabilities.

JavaScript provides built-in functions for simple modal dialogs:

  • Alert box: alert('message') (displays a message and an OK button)
  • Confirm box: confirm('message') (displays a message, OK, and Cancel buttons; returns true or false)
  • Prompt box: prompt('message', 'defaultText') (displays a message, an input field, OK, and Cancel buttons; returns input string or null)

While still functional, these native popups are often considered intrusive and have limited styling options. Modern web applications typically use custom-styled modals or dialogs (e.g., using HTML <dialog> element or UI libraries) for a better user experience.

JavaScript allows you to execute code after a specified time interval or repeatedly at a fixed interval.

  • setTimeout(function, milliseconds, param1, param2, ...): Executes function once after milliseconds. Returns a timer ID.
  • clearTimeout(timerID): Cancels a setTimeout() before it executes.
  • setInterval(function, milliseconds, param1, param2, ...): Executes function repeatedly every milliseconds. Returns an interval ID.
  • clearInterval(intervalID): Stops a setInterval().

For smooth animations, requestAnimationFrame(callback) is preferred over setTimeout or setInterval. It tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.

Client-Side Storage: Cookies and Web Storage

Section titled “Client-Side Storage: Cookies and Web Storage”

Cookies (document.cookie) are small pieces of data stored on the user’s computer by the browser. They are sent with every HTTP request to the same domain. While useful for session management, they have size limitations and can impact performance if overused.

Modern alternatives for client-side storage include the Web Storage API:

  • localStorage: Stores data with no expiration time. Data persists even after the browser window is closed and reopened. (e.g., localStorage.setItem('key', 'value');, localStorage.getItem('key');)
  • sessionStorage: Stores data for one session only. Data is cleared when the browser tab is closed.

Web Storage offers larger storage capacity and a simpler API compared to cookies for client-side data that doesn’t need to be sent with every HTTP request. For more complex client-side data needs, IndexedDB provides a transactional database system.