Subtitle: In this article, we'll talk about one specific relation between JavaScript and web browsers - Browser Object Model.
As JavaScript developers, we should have a basic understanding of the environment in wich JavaScript code is being executed. In web development that environment is a web browser. This article aims to give some insight into object model of browsers.
As we know, in JavaScript there is always a global object defined. This object provides variables and functions that are available anywhere in the code. In a browser environment it is named window
and for Node environment it is named global
.
Recently however, globalThis
was added to the language, as a standardized name for a global object, that should be supported across all environments. In this article we'll use window
for the global object.
When we use JavaScript for web development, we have access to many built-in objects. We can differentiate three types of these objects:
- ECMAScript basic objects,
- DOM - objects that currently loaded website contains (a website is called document) and
- BOM - objects that relate to elements outside the website, like browser window or device screen.
ECMAScript defines a collection of built-in objects for JavaScript. These built-in objects include:
- the global object (globalThis, Infinity, NaN, undefined)
- objects that are fundamental to the runtime semantics of the language including Object, Function, Boolean, Symbol, and various Error objects
- objects that represent and manipulate numeric values including Math, Number, and Date
- the text processing objects String and RegExp
- objects that are indexed collections of values including Array and nine different kinds of Typed Arrays whose elements all have a specific numeric data representation
- keyed collections including Map and Set objects
- objects supporting structured data including the JSON object, ArrayBuffer, SharedArrayBuffer, and DataView
- objects supporting control abstractions including generator functions and Promise objects and
- reflection objects including Proxy and Reflect
DOM is object model for websites, that is documents. It is also important part of the browser environment but it is not topic of this article.
BOM is object model for web browsers. It is a collection of objects that provides informations from web browsers and from computer screen. We access those objects by using the global object window
. Every window, tab, pop-up or iframe in a browser
has its own window
object. Because there is many of those objects, in this article we'll cover just a few of them.
location
property points to the object that contains URL informations of the current document/website. For instance, location.href
holds full URL address, and location.hostname
only a domain. We can list all properties of the location
object by using a simple loop:
for (let i in window.location) {
if (typeof window.location[i] === "string") {
console.log(i + " = " + location[i]);
}
}
As a result, we'll get following properties in the console: href, origin, protocol, host, hostname, port, pathname, search and hash.
The informations that location
object provides are very useful and we can use them when we're making API requests.
location
object also provides three interesting and useful functions: reload(), assign() and replace().
Let's say we're doing a Rest Countries project. Our task is to implement filtering by regions. Further, we'll assume that we are using some kind of reusable select component. This component would then be inserted inside a parent component (homepage).
In our case this select component would contain a list of regions and our code would look something like this:
// we are inside select component
// template of this component is ul list with li items
// every item contains data-region attribute (europe, africa, americas...)
// endpoint: https://restcountries.com/v3.1/region/{region}
regionsList.addEventListener("click", (e) => {
const listItem = e.target.closest("li");
// if clicked outside <li>, we get null,
// and we are stopping the process
if (listItem === null) return;
// when clicked inside <li> proceed and get the attribute
const attribute = listItem.getAttribute("data-region");
// working with URL, setting search parameter
const url = new URL(window.location.origin);
url.searchParams.set("region", attribute);
// replace current querystring with the new one
window.location.assign(url);
});
In this case, after clicking, for instance, the europe region from the list, we create and assign a new url that looks like this: originofwebsite/?region=europe. Now, from our homepage component, by using url.searchParams.get("region")
we are able to get this "europe" part and use it for fetching resources.
history
property allows us to manipulate browser session history (pages visited in the tab or frame that the current page is loaded in). For instance, we can see, how many websites a user has visited before coming to our website. However, we do not get URLs of the visited websites.
console.log(window.history.length);
console.log(window.history.length[0]); // undefined
We can use provided methods to go back or forward in the session history. Try using following methods, which are self explanatory so there is no need for any explanations.
history.forward()
history.back()
history.go(-1)
history.go(-2)
history.go(0)
Modern browsers support HTML5 History API. This API allows changing URL without reloading the page which is perfect for dynamic web applications. It lets us define a specific URL for displaying a certain state of our application. To get better understanding of it, visit any website and type into the console:
history.pushState({a: 1}, "", "hello");
history.pushState({b: 2}, "", "hello-you-too");
history.state;
As a result of doing this, we will see that URL changes without reloading the page. Now experiment with back/next buttons of a browser and check again the history.state
.
In JavaScript we are always working with built-in objects. In this article we learned that these objects come from multiple sources. ECMAScript, for example, defines standard built-in objects for the JavaScript language while browser developers define built-in objects for interacting with the browser.
We covered only location
and history
properties of the global window
object. There are other properties and methods worth exploring, such as frames
, screen
, open()
, close()
etc.
- Object Oriented JavaScript - third edition by Ved Antani and Stoyan Stefanov
- MDN Web Docs