Chapter 9
In This Chapter
Understanding the BOM (Browser Object Model)
Opening and closing windows
Getting windows properties
Resizing windows
“In making theories, always keep a window open so that you can throw one out if necessary.”
— Bela Lugosi
The Browser Object Model (BOM) allows JavaScript to interact with the functionality of the web browser. Using the BOM, you can create and resize windows, display alert messages, and change the current page being displayed in the browser.
In this chapter, you discover what can be done with the browser window and how to use it to write better JavaScript programs.
Web browsers are complicated pieces of software. When they work well, they operate seamlessly and integrate all their functions into a smooth and seemingly simple web browsing experience. We all know that web browsers have an occasional hiccup and sometimes even crash. To understand why this happens, and to be able to make better use of browsers, it’s important to know the many different parts of the web browser and how these parts interact with each other.
The part of the web browser that you interact with when you type in a URL, click the home button, create or use a bookmark, or change your browser settings is called the user interface, or browser chrome (not to be confused with Google’s Chrome browser).
The browser chrome consists of the web browser’s menus, window frames, toolbars, and buttons that are outside of the main content window where web pages load, as shown in Figure 9-1.
The loader is the part of a web browser that communicates with web servers and downloads web pages, scripts, CSS, graphics, and all the other components of a web page. Most often, loading is the part of displaying a web page that creates the longest wait time for the user.
The HTML page is the first part of a web page that must be downloaded, as it contains links and embedded scripts and styles that need to be processed in order to display the page.
Figure 9-2 shows the Chrome Developer Tools’ Network tab. It displays a graphical view of everything that happens during the loading of a web page, along with a timeline showing how long the loading of each part takes.
Once the HTML document is downloaded, browsers will open several connections to the server in order to download the other parts of the web page as quickly as possible. Generally, the parts of a web page that are linked from an HTML document (also known as the resources) are loaded in the order in which they appear in the HTML document. For example, a script that is linked in the head element of the page will be loaded before one that’s linked at the bottom of the page.
JavaScript sometimes affects the display of a web page as well, but more often, it affects only the functionality. When a script will affect the display of a web page, it should be loaded in the head of the document (after the CSS). Scripts that aren’t critical to how the web page appears should be linked from the very end of the body element (right before the </body>
), so as to not create a blocking scenario in which the browser waits for scripts to load before displaying anything to the user.
After a web page is downloaded, the HTML parsing component of the browser goes to work parsing the HTML to create a model (called the Document Object Model or DOM) of the web page. The DOM, which is covered in detail in Chapter 10, is like a map of your web page. JavaScript programmers use this map to manipulate and access all the different parts of a web page.
Upon completion of the HTML parsing, the browser begins downloading the other components of the web page.
Once the CSS for a web page is completely downloaded, the web browser will parse the styles and figure out which ones apply to the HTML document. CSS parsing is a complex process involving multiple passes over a document in order to apply each style correctly and to take into account how the styles impact each other.
The next step in displaying a web page is the JavaScript parsing. The JavaScript parser compiles and runs every script in your web page in the order in which it appears in the document. If your JavaScript code adds or removes elements, text, or styles within the HTML DOM, the browser will update the HTML and CSS renderings accordingly.
Finally, once all the web page's resources have been loaded and parsed, the browser determines how to display the page and then displays it. Unless you’ve specified that a script included earlier in the document should wait until the end to be executed, the layout and rendering of your scripts will occur in the order they’re included in the document.
JavaScript programmers can find out information about a user’s web browser and control aspects of the user’s experience through an API called the Browser Object Model.
There is no official standard for the Browser Object Model. Different browsers implement it in different ways. However, there are some generally accepted standards for how JavaScript interacts with web browsers.
The Navigator
object provides JavaScript with access to information about the user’s web browser. The Navigator
object takes its name from the first web browser to implement it, Netscape Navigator. The Navigator object
isn't built into JavaScript. Rather, it's a feature of web browsers that is accessible using JavaScript. Nearly every web browser (and every modern web browser) has adopted the same terminology to refer to this highest-level browser object.
The Navigator
object accesses helpful information such as
Table 9-1 shows all the properties of the browser Navigator
object.
Table 9-1 The Properties of the Navigator Object
Property |
Use |
|
Gets the code name of the browser |
|
Gets the name of the browser |
|
Gets the browser version information |
|
Tells whether cookies are enabled in the browser |
|
Can be used to locate the user’s physical location |
|
Gets the language of the browser |
|
Identifies whether the browser is online |
|
Gets the platform the browser was compiled for |
|
Gets the browser engine name of the browser |
|
Gets the user-agent the browser sends to web servers. |
To get the properties of the Navigator
object, you use the same syntax used to get the properties of any object — namely, dot notation or brackets notation. Listing , when opened in a web browser, will display all the current properties and values of the Navigator
object.
Listing 9-1: Properties of the Navigator Object and Their Values
<html>
<head>
<style>
.columns {
-webkit-column-count: 6; /* Chrome, Safari, Opera */
-moz-column-count: 6; /* Firefox */
column-count: 6;
}
</style>
</head>
<body>
<div class="columns">
<script>
for (var prop in navigator){
document.write (prop + ": " + navigator[prop] + "<br>");
}
</script>
</div>
</body>
</html>
Figure 9-3 shows the output of Listing 9-1 when opened in a web browser.
If you run Listing 9-1 yourself, you’ll notice something interesting about the output: The values for the AppName
properties are seemingly just plain wrong. For example, the browser used to generate the Figure 9-3 was Google Chrome, but AppName
lists it as Netscape.
This misleading value is a relic from the days when programmers used the properties of the Navigator
object to detect whether a user was using a particular browser and supported certain features.
When new browsers, such as Chrome and Firefox, came along, those browsers adopted the Netscape browser AppName
value in order to make sure they were compatible with websites that detected features in this way.
var test_audio= document.createElement("audio");
if (test_audio.play) {
console.log ("Browser supports HTML5 audio");
} else {
console.log ("Browser doesn't support HTML5 audio");
}
The main area of a web browser is called the window. This is the area into which HTML documents (and associated resources) load. Each tab in a web browser is represented in JavaScript by an instance of the Window
object. The Window
object’s properties are listed in Table 9-2.
Table 9-2 The Window Object’s Properties
Property |
Use |
|
A Boolean value indicating whether a window has been closed or not |
|
Gets or sets the default text in the status bar of a window |
|
Refers to the |
|
Gets the element, such as |
|
Lists all the subframes in the current window |
|
Gets the user’s browser history for the current window. |
|
Gets the inner height of the window |
|
Gets the inner width of the window |
|
Gets the number of frames in the window |
|
Gets the |
|
Gets or sets the name of the window |
|
Gets the |
|
Gets the |
|
Gets the outer height of the window, including scrollbars and toolbars |
|
Gets the number of pixels that have been scrolled horizontally in the window |
|
Gets the number of pixels that have been scrolled vertically in the window |
|
Refers to the parent of the current window |
|
Refers to the |
|
Gets the horizontal pixel distance from the left side of the main screen to the left side of the current window |
|
Gets the vertical pixel distance from the top of the window relative to the top of the screen |
|
Gets the horizontal coordinate relative to the screen |
|
Gets the vertical coordinate relative to the screen |
|
Refers to the current window |
|
Refers to the topmost browser window |
Some of the most common uses for the window properties include
Getting the value of the window.location
property will return the URL of the current page. Setting the value of the window.location
property with a new URL causes the browser to load the web page at that URL in the window.
Listing 9-2 is a web page with a script that requests a web page address from the user and then loads that page in the current browser window.
Listing 9-2: A Script for Loading a Web Page in the Browser Window Using the window.location Property
<html>
<head>
<script>
function loadNewPage (url){
window.location = url;
}
</script>
</head>
<body>
<script>
var newURL = prompt("Please enter a web page address!");
loadNewPage(newURL);
</script>
</body>
</html>
Figure 9-4 shows the output of Listing 9-2.
When you’re designing a website or a web application to work and function on different types of devices (a technique known as responsive design), knowing the size of the web browser, particularly the width, is critical.
The window.innerWidth
and window.innerHeight
properties give you this information, in pixels, for the current web browser window.
Try a simple responsive design example using JavaScript. Run the program in Listing 9-3 in your web browser. If your web browser window width is below 500 pixels, one message will be displayed. If your window’s width is greater than 500 pixels, a different message will be displayed.
Listing 9-3: Changing a Web Page Based on the Width of the Window
<html>
<head>
<title>Adapting to the window.innerWidth</title>
</head>
<body>
<script>
var currentWidth = window.innerWidth;
if (currentWidth > 500) {
document.write("<h1>Your window is big.</h1>");
} else {
document.write("<h1>Your window is small.</h1>");
}
</script>
</body>
</html>
To test out the responsive design example in Listing 9-3, follow these steps:
In your web browser, open an HTML document containing the code in Listing 9-3.
If your window is more than 500px wide when you open your page, you’ll see a message that your window is big.
Click your browser’s refresh button, or press Command+R (on Mac) or Ctrl+R (on Windows), to reload the page.
Notice that the message on the page now says your browser’s window is small.
The history property of the window object is a read-only reference to the history object, which stores information about the pages the user has accessed in the current browser window. By far the most common use of the history object is to enable buttons that return the user to a previously viewed page.
Listing 9-4: Implementing a Back Button in a Web Application
<html>
<head>
<title>Creating a Back button</title>
<script>
function takeMeBack () {
window.location(window.history.go(-1));
}
function getHistoryLength () {
var l = window.history.length;
return l;
}
</script>
</head>
<body>
<script>
var historyLength = getHistoryLength();
document.write ("<p>Welcome! The number of pages you've visited in this window is: " + historyLength + ".</p> ");
</script>
<br>
<a href="javascript:void(0);" onclick="takeMeBack();">Go Back</a>
</body>
</html>
To use the back button in Listing 9-4, follow these steps:
www.watzthis.com
.
Click the Go Back link.
Your browser will take you back to the last page you visited before the one containing the Back button.
Window
object’s methodsIn addition to its properties, the Window
object also has some useful methods that JavaScript programmers should know and use. Table 9-3 shows the complete list of these methods.
Table 9-3 The Window Object's Methods
Method |
Use |
|
Displays an alert box with a message and an OK button |
|
Decodes a base-64 encoded string |
|
Causes the current window to lose focus |
|
Cancels the timer set using setInterval() |
|
Cancels the timer set using setTimeout() |
|
Closes the current window or notification |
|
Displays a dialogue box with an optional message and two buttons; OK and Cancel |
|
Creates a pop-up window |
|
Sets the current window into focus |
|
Moves the current window by a specified amount |
|
Relocates a window to a specified position |
|
Opens a new window |
|
Prints the contents of the current window |
|
Displays a dialogue box prompting the user for input |
|
Resizes the window by a specified number of pixels |
|
Resizes a window to a specified height and width. |
|
Scrolls the document by a specified amount |
|
Scrolls the document to a specific set of coordinates |
|
Calls a function or executes an expression repeatedly at specified intervals (in milliseconds) |
|
Calls a function or executes an expression after a specified interval (in milliseconds) |
|
Stops the current window from loading |