Chapter 9

Controlling the Browser with the Window Object

In This Chapter

arrow Understanding the BOM (Browser Object Model)

arrow Opening and closing windows

arrow Getting windows properties

arrow 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.

Understanding the Browser Environment

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 user interface

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.

image

Figure 9-1: The browser chrome.

Loader

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.

image

Figure 9-2: Web browser loading.

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.

remember The load order of resources is critical to the efficiency and speed at which the page can be displayed to the user. In order for a web page to be displayed correctly, the CSS styles that apply to that page need to be loaded and parsed. Because of this, CSS should always be loaded in the head element at the top of the web 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.

HTML parsing

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.

CSS parsing

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.

JavaScript parsing

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.

Layout and rendering

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.

tip In general, it’s better to display a web page to the user as quickly as possible, even if the page may not be fully functional when it first appears. Modern websites frequently employ this strategy specifically (called deferred loading) to improve the perceived performance of their pages. If you’ve ever opened a web page and had to wait for a moment before you can use a form or interactive element, you’ve seen deferred loading in action.

Igniting the BOM

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

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

  • The name of the web browser
  • The version of the web browser
  • The physical location of the computer the browser is running on (if the user allows the browser to access geolocation data).
  • The language of the browser
  • The type of computer the browser is running on

Table 9-1 shows all the properties of the browser Navigator object.

Table 9-1 The Properties of the Navigator Object

Property

Use

appCodeName

Gets the code name of the browser

appName

Gets the name of the browser

appVersion

Gets the browser version information

cookieEnabled

Tells whether cookies are enabled in the browser

geolocation

Can be used to locate the user’s physical location

language

Gets the language of the browser

onLine

Identifies whether the browser is online

platform

Gets the platform the browser was compiled for

product

Gets the browser engine name of the browser

userAgent

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.

image

Figure 9-3: Listing all of the properties of the Navigator object with their values.

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.

warning Today, browser detection isn’t recommended, and you can use better ways to detect browser support for particular functionality than by looking at the AppName property. The most common way to detect features today is by examining the DOM for objects associated with the feature you want to use. For example, if you want to find out if a browser supports the HTML5 audio element, you can use the following test:

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 Window object

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

closed

A Boolean value indicating whether a window has been closed or not

defaultStatus

Gets or sets the default text in the status bar of a window

document

Refers to the Document object for the window

frameElement

Gets the element, such as <iframe> or <object>, that the window is embedded in

frames

Lists all the subframes in the current window

history

Gets the user’s browser history for the current window.

innerHeight

Gets the inner height of the window

innerWidth

Gets the inner width of the window

length

Gets the number of frames in the window

location

Gets the Location object for the window

name

Gets or sets the name of the window

navigator

Gets the Navigator object for the window

opener

Gets the Window object that created the current window

outerHeight

Gets the outer height of the window, including scrollbars and toolbars

pageXOffset

Gets the number of pixels that have been scrolled horizontally in the window

pageYOffset

Gets the number of pixels that have been scrolled vertically in the window

parent

Refers to the parent of the current window

screen

Refers to the Screen object of the window

screenLeft

Gets the horizontal pixel distance from the left side of the main screen to the left side of the current window

screenTop

Gets the vertical pixel distance from the top of the window relative to the top of the screen

screenX

Gets the horizontal coordinate relative to the screen

screenY

Gets the vertical coordinate relative to the screen

self

Refers to the current window

top

Refers to the topmost browser window

Some of the most common uses for the window properties include

  • Opening a new location in the browsers window
  • Finding the size of a browser window
  • Returning to a previously open page (as in the back button functionality)

Opening a web page with the window.location property

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.

image

Figure 9-4: The window.location property in action.

Determining the size of a browser window

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.

technicalstuff Using CSS to determine the size of a browser window is also possible and quite common. However, there are some differences in how CSS and JavaScript treat scrollbars that may influence which technique you decide to use.

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:

  1. 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.

  2. Drag the lower right corner of your browser to make the window as narrow as you can, as shown in Figure 9-5.
  3. 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.

image

Figure 9-5: Displaying a different message for narrow browser width.

Creating a Back button using location and history

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:

  1. Open a new browser window and visit any page you like, such as www.watzthis.com .
  2. While in that same browser window, open an HTML document containing the code in Listing 9-4.
  3. Click the Go Back link.

    Your browser will take you back to the last page you visited before the one containing the Back button.

tip Care to guess what happens if you open Listing 9-4 in a new browser tab before accessing any other web pages in that tab? If you guessed that nothing will happen, you're correct! If only ONE page (the current one) has been displayed in a window, there's nothing to go back to.

Using the Window object’s methods

In 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

alert()

Displays an alert box with a message and an OK button

atob()

Decodes a base-64 encoded string

blur()

Causes the current window to lose focus

clearInterval()

Cancels the timer set using setInterval()

clearTimeout()

Cancels the timer set using setTimeout()

close()

Closes the current window or notification

confirm()

Displays a dialogue box with an optional message and two buttons; OK and Cancel

createPopup()

Creates a pop-up window

focus()

Sets the current window into focus

moveBy()

Moves the current window by a specified amount

moveTo()

Relocates a window to a specified position

open()

Opens a new window

print()

Prints the contents of the current window

prompt()

Displays a dialogue box prompting the user for input

resizeBy()

Resizes the window by a specified number of pixels

resizeTo()

Resizes a window to a specified height and width.

scrollBy()

Scrolls the document by a specified amount

scrollTo()

Scrolls the document to a specific set of coordinates

setInterval()

Calls a function or executes an expression repeatedly at specified intervals (in milliseconds)

setTimeout()

Calls a function or executes an expression after a specified interval (in milliseconds)

stop()

Stops the current window from loading

remember A method is just another name for a function that's contained within an object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset