Reliable JavaScript Certification Online #

The Browser Object Model (BOM) is the core of JavaScript in web browser. It consists of objects that provide browser functionality independent of the web page content.

 

The window object

Core of the BOM is the window object implementing the Window interface defined by W3C. The window object represents web browser window and simultaneously the ECMAScript Global object.

The global scope

The window object is also the global object. All variables and functions declared in the global scope become properties and methods of the window object.

var x = 10;
function displayX() {
    alert('The x is: ' + x);
}

alert(window.x); // 10
window.displayX(); // The x is: 10

//The result is the same for:
alert(x); // 10
displayX(); // The x is: 10

A variable x and a function displayX are declared globally, therefore automatically became respectively the property and the method of the window object.

Using this operator in the global scope you will refer to the window object.

var y = 20;

function displayY() {
    alert('This is y: ' + this.y);
}

this.displayY();

There is a difference between global variables and directly defined window properties. You can remove properties defined directly using the delete operator, but you can not do this for global variables.

var z = 30;
delete window.z;  // this returns false and do not delete the z property
console.log(window.z); // 30

window.t = 40;
delete window.t; // returns true
console.log(window.t); // undefined

Note that there are many build-in objects (like location) and functions (like alert(), setTimeout()) considered global which in fact are properties and methods of the window object.

Window size

There are four properties which specify the size of a window:

The window.innerWidth and window.innerHeight mean the size of the page viewport in the browser window (except toolbars and borders).

The window.outerWidth and window.outerHeight mean the size of the whole browser window including toolbars and borders.

All these properties are read-only.

var pageHeight = window.innerHeight;
var windowHeight = window.outerHeight;

The window object provides two methods which you can use to resize a window.
The resizeTo() expects two arguments: a new width and height and resizes window to given dimensions.
The resizeBy() in turn expects two arguments which are differences in each size.

window.resizeTo(600, 400); // resize to 600 x 400
window.resizeBy(200, 100); // resize to 800 x 500

Window position

The position of a window specify two properties:
The window.screenX and window.screenY indicate coordinates relative to the screen in CSS pixels. This is a distance of the left and top border of the browser window from the left and upper point of the screen. Both properties are read-only.

var left = window.screenX; 
var top = window.screenY;

To move the window to a new position the window object provides two methods.
The window.moveTo() expects the x and y coordinates to move to.
The window.moveBy() also expects two arguments, number of pixels to move in each direction.

window.moveTo(10, 20); // move the window to the position x = 10, y = 20
window.moveBy(50, 30); // move the window right by 50 pixels and down by 30 pixels

Opening and closing windows

JavaScript allows you to open new browser windows (or tabs, depending on a browser configuration) from the current window. The window.open() method opens specified URL in a new window (or in existing one). It accepts four optional arguments:

The url specifies the URL of the document to load. If it is not supplied, a blank page is displayed and the URL is set to about:blank.

window.open('http://example.com');

The second argument, target specifies the name of a window. If a window with this name already exists, that window is used to load the URL. Otherwise a new window with the given name is created. If this argument is omitted the special window name _blank is used and it opens an unnamed window.

window.open('http://example.com', 'myWindow');

There are four special window names that may be used: _blank to open a new blank window, _self to load a new URL into the current window, _parent to use parent window and _top to use top level ancestor window.

The third argument is the settings. It is comma-separated list of window settings (without spaces). If it is omitted a new browser window is opened with the default settings. See below the list of possible settings:

 

Setting Possible value Description
left Number The left position of the new window
top Number The top position of the new window
width Number The width of the new window, minimum value is 100
height Number The height of the new window, minimum value is 100
menubar [“yes”, “no”, 1, 0] Specifies whether to display the menu bar, the default is “no”
location [“yes”, “no, 1, 0”] Specifies whether to display (enable) the location bar, the default depends on the browser
toolbar [“yes”, “no”, 1, 0] Specifies whether to display the status bar, the default is “no”
status [“yes”, “no”, 1, 0] Specifies whether to display the status bar, the default depends on browser
scrollbars [“yes”, “no”, 1, 0] Specifies whether scrolling is allowed, the default is “no”
resizable [“yes”, “no”, 1, 0] Specifies whether resizing is allowed, the default is “no”

 

window.open("https://example.com", _blank,"width=300,height=250,toolbar=yes,status=yes");

The fourth argument replace specifies whether the URL should replace the current entry in the history of browsing or should create a new entry.

The window.open() methods returns a reference to the new window. It is the Window object and you can use it to refer to this new window.

var smartWindow = window.open();
smartWindow.alert("You will be redirected to http://example.net");
smartWindow.location = "http://example.net";

From the newly opened window you can refer to this window from which it was opened. The Window object has the opener property that refers to the window which called window.open(). If the window was not open by calling window.open(), the opener is null.

var windowOpener = window.opener;
if (windowOpener !== null) {
    // this alert will open in the window that opened window with this code
    windowOpener.alert("message from the new window: opened successfully"); 
}

To close a window simply use window.close() method.

window.close();

Note that browsers only allow you to automatically close the windows created by window.open() of the same origin. Closing the main window is not possible automatically.

 

Dialog boxes

Browser window allows you to display simple dialog boxes to the user. There are alert(), confirm() and prompt() methods. These dialogs do not contain HTML and CSS formatting but plain text. Their appearance depend on browser and operating system.

In addition, all these dialogs are blocking. When the dialog is displayed a further code execution stops until the user dismisses this dialog. So if the dialog is displayed when the page is loaded, further rendering is stopped until the user closes this dialog.

The alert() method displays a message to the user. It accepts a string as an argument. When the alert() is called, the browser displays dialog box with passed text and below a OK button. The only possibility for the user is to dismiss the dialog after displaying the message.

alert("welcome to the website");

The confirm() method displays a message to the user and expects confirmation. The method accepts a string as an argument. Dialog box in addition to the text message displays two buttons: OK and Cancel. The user can confirm or cancel the message. If the user clicks OK, the confirm() returns true, if he clicks Cancel it returns false. This allows the user to decide on the next action.

var confirmed = confirm("Are you sure to delete this item?");
if (confirmed) {
    // here the code that removes the item
}

The prompt() method displays a message and prompts the user to enter a data. The method accepts two string arguments: the text to display and the default value for the input. Dialog box displays a text message, text input, where user can enter a data and buttons OK and Cancel. It returns entered data if user clicks OK and null otherwise.

var favorite = prompt("Your favorite programming language:", "JavaScript");

 

Timers

JavaScript allows you to run the code at specific time points and execute it once or repeatedly. For this you can use the global functions setTimeout() and setInterval() which are in fact methods of the Window.

The setTimeout() method allows you to execute code after a specific amount of time. It accepts two arguments: the code to execute and the number of milliseconds to wait before executing the code. After calling the setTimeout() returns an unique identifier of the timeout.

var displayTimMsg = function() {
    var msg = "Time is up!";
    alert(msg);
};
setTimeout(displayTimMsg, 2000);

The setInterval() method is similar to the setTimeout(). The difference between them is that the setInterval() executes code repeatedly at intervals of a specific time. This is done until the page is unloaded or the interval canceled. The setInterval() also accepts two arguments: the code to execute and time in milliseconds to wait between executions. After calling the setInterval() returns an unique identifier of the interval.

var displayIntMsg = function() {
    var msg = "The next interval has passed!";
    alert(msg);
};
setInterval(displayIntMsg, 3000);

You can cancel a scheduled code execution. To do this use the clearTimeout() method which as argument expects a timeout identifier or an interval identifier:

var timeoutId = setTimeout(displayTimMsg, 2000);
var intervalId = setInterval(displayIntMsg, 3000);

clearTimeout(timeoutId); // timeout canceled
clearTimeout(intervalId); // interval canceled

Note that both setTimeout() and setInterval() accept as the code to execute function or string. However the second way is not recommended.

// Not recommended:
setTimeout("var msg = 'Hello!'; alert(msg);", 2000);

// Recommended:
setTimeout(function(){
    var msg = 'Hello!';
    alert(msg);
}, 2000);

 

The location object

The location is the property of the Window object type and refers to object of the Location object type. It represents the URL of the currently loaded document in the browser window. The properties of the location object provide detailed information about the url and its parts:

The href property is a string that contains full URL of the currently loaded page. For example The toString() method returns the value of this property. So in the context that will call toString() you can simply write location instead of location.href to get the full url.

The protocol property contains the protocol used by the page (usually http: or https:).

The hostname property returns the name of the server (usually domain).

The host property returns the name of the server and the port (if presented).

The port property returns the port of the request if specified or empty string otherwise.

The pathname property returns the path identified the specific resource (directory, filename).

The search property returns the query string, beginning with a question mark (?) list of key-value pairs of params separated by ampersand (&) and specifying details of the request.

The hash property returns the optional fragment identifier, it begins with hash mark (#) and is followed by an element ID in the document.

// asume that current URL is: http://www.example.net/api/?type=course&langauge=js#topics
// location properties values:
location.href; // http://www.example.net/api/?type=course&langauge=js#topics
location.protocol; // http:
location.hostname; // www.example.net
location.host; // www.example.net:8080
location.port; // 8080
location.pathname; // /api/
location.search; // ?type=course&langauge=js
location.hash; // #topics

Changing the location

The location can be changed is several ways. You can simply assign a new URL to the location href property:

location.href = 'http://example.net';

Even simpler, you can assign a new URL directly to the location:

location = 'http://example.net';

The next option is to use the assign() method:

location.assing('http://example.net');

Not only the entire URL but also its individual parts can be changed by changing the properties of the location object.

 // Assume that there is loaded a page with the URL http://www.example.net/api/?type=course#topics

location.hostname = 'www.example.com'; // changes URL to http://www.example.com/api/?type=course#topics

location.pathname = 'api2'; // changes URL to http://www.example.net/api2/?type=course#topics

location.search = '?type=course&language=js'; // changes URL to http://www.example.net/api/?type=course&language=js#topics

location.hash = '#resources'; // changes URL to http://www.example.net/api/?type=course#resources

Change of a location property, except of the hash, causes that the page reloads.

 

The navigator object

The navigator is the property of the Window object type and refers to object of the Navigator object type. It provides information about the user’s browser, such as the vendor and the version of the browser. The navigator contains number of properties which describe client-side data. See the most important of them below:

The appName is the full name of the browser. But for historical reasons (in order to display the content correctly) most browsers have set it to “Navigator”

The appCodeName – the name of the browser, not very useful, as most of browsers have it set to “Mozilla”.

The appVersion – browser version, the number 5.0 at the beginning indicates fifth-generation browser, then information on browser vendor and version, it may not be accurate.
The cookieEnabled – indicates whether cookies are enabled.

The geolocation – object providing information on location of the user.

The language – returns primary language of the browser.

The mimeTypes – returns mime types supported by the browser.

The onLine – indicates whether the browser is online.

The oscpu – information about operating system.

The platform – information about system platform, it may not be correct.

The plugins – list of plugins installed in the browser.

The product – always is set to “Gecko”, it is kept from historical reasons.

The userAgent – string providing information about the browser name, version and operating system, it is used to identify user’s browser.

The activeVRDisplays – returns list of VRDisplay objects.

The connection – returns object providing information on the network connection of a device.

The serviceWorker – returns ServiceWorkerContainer object, which provides access to ServiceWorker objects.

 

The history object

The history is the property of the Window object type and refers to the object of the History object type. The history object represents the browsing history of a window. However for security reasons it is not possible to get the URLs which user has visited.
Instead of this, the history object provides methods for navigating back and forward in the browsing history without knowing the urls of visited pages:

The back() method works like the browser’s Back button. It causes that the browser go backward one step in the browsing history and displays the previous page.

history.back(); // go back one step

The forward() method works like the browser’s Forward button. It causes that the browser go forward one step in the browsing history and displays the following page.

history.back(); // go forward one step

The go() method navigates in both directions of browsing history, backward and forward, additionally it can skip any number of pages. The go() method accepts an integer argument, that indicates the number of pages to go back (for negative numbers), or to go forward (for positive numbers);

history.go(-2); // go back two pages

history.go(1); // go forward one page

The history object provides also the the length property. It specifies the number of items in the browsing history list.