The JavaScript BOM
The JavaScript DOM gets all the attention of coders, developers, and also learners; its lesser-known cousin—the Browser Object Model (BOM)—quietly powers some of the most useful browser features. Unlike the JavaScript DOM, which deals with page content, the BOM gives you access to everything around the webpage, meaning it gives you access to the browser window itself, screen size, navigation history, and more.
The Window Object
At the center of the BOM is the window
object that is considered the global parent of everything in your JavaScript code. Every variable and function you create in the code is already placed inside this window object.
As expected, the window
object can give you the access to do some interesting manipulation in your browser window. Some practical things you can do with it:
- Open or close browser windows using
window.open()
andwindow.close()
. - Get screen dimensions with
window.innerWidth
andwindow.screen
. - Control scrolling (
window.scrollTo()
). - Set timers (
setTimeout()
,setInterval()
)
BOM Features You Should Know
Location Object
if you want to redirect website users or check their current URL. Use the location object to do this; use it as follows:
// Redirect to a new page
window.location.href = "https://jsbites.info";
// Reload the current page
window.location.reload();
History Object
An object to help you navigate back/forward programmatically:
// Go back one page (like using the back button)
window.history.back();
// Go forward
window.history.forward();
Navigator Object
An object to detect browser details and capabilities:
// Check if cookies are enabled
const cookiesEnabled = navigator.cookieEnabled;
// Get browser name
const browserName = navigator.userAgent;
JavaScript BOM Importance
Nowadays, while JavaScript modern frameworks often abstract these features away, understanding the BOM helps you have:
- More control over the user's browsing experience
- The ability to create custom navigation flows
- Fallback options when framework features aren't enough
- Tools to optimize for different devices and browsers
A Caution
Notice that some BOM methods (e.g., window.open() the one used for popups) are most times annoying to users if overused. So always consider user experience when implementing BOM features.
Conclusion
The BOM might not be as flashy as the DOM, but it's just as important for creating robust web experiences. When you need to interact with the browser itself rather than page content, remember that the JavaScript BOM can help you.