Computer scienceProgramming languagesJavaScriptInteraction with a browserBrowser Window

Window Object

4 minutes read

Warm-up game: spot the nearest window! Where are you looking? It's right here: you are reading this topic in one of them! Window Object is an object that represents a browser window. It provides the JavaScript browser interaction interface. If an HTML document contains an <iframe> tag, the browser creates one Window Object for the HTML document and one Window Object for each such tag in the document.

Let's take a closer look at the properties and methods of this object.

Properties

One of the features of the Window Object is that it is global. This means that access to its properties and methods can be carried out from anywhere in the program. Look at an example of accessing a closed property which returns true or false depending on whether the window is closed or not:

console.log(window.closed);

It can also be written as follows:

console.log(closed);

As you see, this can be done without specifying the Window Object.

Let's look at another property:

console.log(innerHeight);

It returns the height of the current window. And here is the innerWidth property:

console.log(innerWidth);

It contains the value of the width of the window.

We couldn't possibly fit all properties here, so we're inviting you to check out the full list of properties yourself.

Methods

In order to create a new empty browser window, use the following method:

open();

You can specify the URL as a parameter, for example, open a new window with the Hyperskill website:

open("https://hyperskill.org/");

To close the current window, use the close() method:

close();

Keep it in mind: JavaScript can only close the window that was opened with it!

Another important method is calling an alert window that contains a message and an OK button. For example, try entering the following code in the console:

alert("Hello Hyperskill!");

A similar method is confirm():

confirm("Hyperskill is excellent");

However, while alert() does not return anything, confirm() returns true if the OK button was pressed and false if the user clicked Cancel.

Again, this is not a complete list of methods, so we invite you to check out other methods.

Conclusion

Today we considered an important type of object, Window Object. In the context of browsers, it is important to know that the window object is not part of JS itself (not part of the spec), that is why other environments don’t have any Window Object. Remember that this object is global, so access to its properties and methods is possible from anywhere in the program and without specifying an object. It has an extensive list of properties and methods, some of which we considered here.

187 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo