About
In this code snippet, we’ll learn how to access the browser object model(BOM) with Javascript.
We can use the BOM to interact with the browser itself and get information like screen resolution, window size, OS, language, … We can also open/close windows/tabs, navigate back/forward in history.
Note: There are too many properties in the window object to cover here. Consult the MDN documentation for anything more specific.
Let’s see some examples below.
Code:
//Page//////////////////////////////////// //All properties: https://developer.mozilla.org/en-US/docs/Web/API/Window window.open(); //Opens new tab. window.close(); //Closes tab. //window.navigator//////////////////////// //All properties: https://developer.mozilla.org/en-US/docs/Web/API/Navigator console.log(window.navigator.appName); console.log(window.navigator.appCodeName); console.log(window.navigator.platform); console.log(window.navigator.userAgent); //window.location./////////////////////// //All properties: https://developer.mozilla.org/en-US/docs/Web/API/Window/location console.log(window.location.href); console.log(window.location.hostname); console.log(window.location.pathname); console.log(window.location.protocol); window.location.reload(); //Reloads page. //window.history///////////////////////// //All properties: https://developer.mozilla.org/en-US/docs/Web/API/Window/history window.history.back() //One page back. window.history.forward(); //One page forward. //window.Screen///////////////////////// //All properties: https://developer.mozilla.org/en-US/docs/Web/API/Window/screen console.log(window.screen.width); console.log(window.screen.height); console.log(window.screen.pixelDepth);