Chapter 11. Scripting Windows

Dialog boxes and the location object are far from all the window object has to offer developers. In fact, this object is often used to open and manipulate new windows.

OPENING NEW WINDOWS

Even though the advent of pop-up blockers greatly (and rightly) diminished the use of opening new windows through script, you can still find the practice legitimately used by many web-based applications. The key to this functionality is the open() method. It accepts four optional arguments, and returns the window object of the newly created window (dubbed the child window in this text).

The first parameter of the method is the URL of the web page you want to open in the child window; passing an empty string causes the child window to open a blank page. The second parameter, if specified, is the name you want to give to the new window. This name corresponds with the value given to the target attribute in hyperlinks. The following HTML is an example:

<a href="http://www.microsoft.com" target="childWindow">Microsoft.com</a>

If you were to open a new window with JavaScript and give it the name childWindow, clicking this link would load www.microsoft.com in the newly opened window. Of course, omit the second parameter if you do not wish the window to be a target for links.

The third parameter is a list of options and properties that determine how the child window looks. These options and properties include, but are not limited to, width, height, and whether user interface elements are visible to the user. There's a lengthy list of options to choose from, and you'll see a shortened list in a few moments. For now, let's just stick with height and width with this simple example:

var childWindow = open("http://www.google.com", "googleWindow",
    "height=400, width=400");

Here the open() method is called (the window object is implied before open()), and the child's window object is stored in the childWindow variable. The first argument passed to the method is the URL for Google's home page. Its name is googleWindow, so any hyperlink in the main document with the same target value opens its URL in this new window. Notice the third argument: It looks a little different from other arguments you've seen so far. The third argument is a string that contains one or more options separated by commas. In this example the height and width options are assigned values of 400, and a comma separates the two options. Figure 11-1 shows the window this code opens in Chrome.

Figure 11-1

Figure 11.1. Figure 11-1

The third parameter is completely optional; you don't have to specify any options or settings for the new window. If you do, however, you can add any of the following options to control how the window looks or behaves.

New Window Options

OPTION

POSSIBLE VALUES

DESCRIPTION

height

integer

The height of the new window in pixels

left

integer

The horizontal position of the new window

location

yes, no

Shows the location bar (Doesn't work in Opera)

menubar

yes, no

Shows the menu bar (Doesn't work in Opera or Safari)

resizable

yes, no

Determines whether or not the user can resize the window

scrollbars

yes, no

Shows the horizontal and/or vertical scrollbars if the page is too large to fit in the window

status

yes, no

Shows the status bar (Doesn't work in Opera)

toolbar

yes, no

Shows the toolbar (Doesn't work in Opera)

top

integer

The vertical position of the new window

width

integer

The width of the new window in pixels

Keep in mind this list is not exhaustive, but these are the most commonly used options for a new window. Consider the following code to get an idea of how to apply some of these options:

var childWindow = open("http://www.google.com", "googleWindow",
    "height=400, width=400, resizable=no, menubar=no");

Here two more options are added to the open() method's third parameter. The new window is no longer resizable by the user, and it does not display the menu bar. Figure 11-2 shows the window generated from this code in Internet Explorer 8.

Figure 11-2

Figure 11.2. Figure 11-2

The fourth parameter is a Boolean value that determines whether the URL specified in the first argument creates a new entry or replaces the current entry in the browser's history list if the page is loaded into an already existing window. If true, the URL replaces the current document in the history list. If false, a new entry is created in the history.

MANIPULATING WINDOWS

Unfortunately, you can't change the properties listed in the previous table once a window is opened. You can, however, change the window's dimensions and position. Instead of using the height, width, top, and left properties in the previous table, you must use four special methods that perform these actions.

Before looking at these methods, especially the positional methods, you need to know how coordinates are translated on the screen. The computer screen is a coordinate system of pixels. The top left pixel on the screen is the origin, or 0, 0 (x, y). As you move down the y-axis of the screen, each pixel is a consecutive positive number. So the pixel directly below the origin has a vertical position of 1, the pixel below that has a vertical position of 2, and so on. As you move to the right on the x-axis, each pixel is a consecutive positive number. This means the pixel directly to the right of the origin has a horizontal position of 1, the one next to it has a horizontal position of 2, and so on. Figure 11-3 illustrates this coordinate plane.

Figure 11-3

Figure 11.3. Figure 11-3

You use this coordinate system to position a window by specifying its horizontal and vertical position when using the moveTo() method. The following code opens a window and positions it on the screen at (100, 100). Figure 11-4 shows the results of the following code:

var childWindow = open("http://www.google.com", "", "height=300, width=300");

childWindow.moveTo(100, 100);
Figure 11-4

Figure 11.4. Figure 11-4

Here, the moveTo() method moves the window 100 pixels to the right and 100 pixels down from the origin. The first argument passed to moveTo() is the new horizontal (x) position, and the second is the new vertical (y) position. This method moves the window in relation to the entire screen. So this code moves the window 100 pixels from the left and top edges of the screen. If you wanted to move the window from its current position of (100, 100) by four pixels to the left and two pixels down, you could use this line of code:

childWindow.moveTo(100 - 4, 100 + 2);

You can, however, use another method called moveBy() to perform the same action. This method moves the window by the specified values in relation to the window's current position. So instead of performing arithmetic, as in the previous example, simply use the moveBy() method and supply the number of pixels to move the window by, like this:

childWindow.moveBy(−4, 2);

This line of code provides the same results as the previous example. Instead of moving the window to the coordinates (−4, 2), it moves the window four pixels to the left and two pixels down from its current position of (100, 100). Given a specific point on the screen, positive numbers move the window to the right and down; negative numbers move the window to the left and up.

Repositioning windows isn't the only way you can manipulate them after creating them; you can also change their height and width with methods similar in concept to the moveTo() and moveBy() methods. The first method is resizeTo(), and it allows you to specify the new width and height of the window, like this:

childWindow.resizeTo(100, 200);

Here the resizeTo() method resizes the window to have a width of 100 and a height of 200. Figure 11-5 shows what this code does to the window created earlier in this section.

Figure 11-5

Figure 11.5. Figure 11-5

If you want to resize the window in relation to its current dimensions, simply use the resizeBy() method. The following code shrinks the window's width by 50 pixels and expands its height by 100:

childWindow.resizeBy(−50, 100);

Browsers allow you to manipulate the parent window by using these methods. It is strongly recommended that you do not do so. Our primary goal as web developers is to provide usable and friendly web applications to our users. Resizing and moving the main window breaks the friendliness of our applications. As a general rule of thumb, move and resize only the windows you open, and leave the windows the user opens alone.

Changing a window's size or position isn't the only way to interact with a window created with the open() method. Parent and child windows can communicate with each other using JavaScript.

CODING BETWEEN WINDOWS

Remember that the open() method returns the new window's window object, so you can access just about anything within the window by using the child's window object. For example, look at this code:

var childWindow = open("http://www.google.com");

childWindow.alert("Hello there!");

Here a new window is opened to www.google.com, and its window object is assigned to the childWindow variable. The next line uses this object and calls its alert() method, displaying an alert box in the child window. So by executing this code, the JavaScript code in the main window communicates with the window object of the child window. Using this methodology, you can tell the child window to navigate to a different page by using the location object, like this:

childWindow.location = "http://www.microsoft.com";

Here the child window navigates to Microsoft's website by assigning a new value to the location object.

Cross-window communication is not a one-way street — the child window also has the ability to communicate with the parent's window object by using the opener keyword. This keyword is used inside the child window to reference the parent window. The following code demonstrates the use of the opener property:

opener.alert("Hello from the child!");

In this code, an alert box displays a message in the parent window even though it is executed from the child window. You can also access the parent's location object — simply prefix it with opener as shown here:

opener.location = "http://www.google.com";

In this line of code, the child window tells the parent window to navigate to Google's home page. The fun doesn't end here, however. Not only can you access the window objects of both parent and child windows, but you can also access each window's JavaScript code. The following code is an HTML page. Let's refer to it as Page 1:

<html>
<head>
    <title>Page 1</title>
    <script type="text/javascript">
        function showMessage(message) {
            alert(message);
        }

        var childWindow = open("page2.htm");
    </script>
</head>
<body>

</body>
</html>

Focus on the <script/> element. It creates a function called showMessage() that accepts one argument called message. The value passed to this function is then passed to the alert() method. The last line of the <script/> element opens a new window, which we'll call Page 2. Its HTML follows:

<html>
<head>
    <title>Page 2</title>
    <script type="text/javascript">
        opener.showMessage("Hello from Page 2!");
    </script>
</head>
<body>

</body>
</html>

The script in this page has only one line; it uses the opener object to call the showMessage() method (remember that global variables and functions are actually properties and methods of the window object). So this is what happens when you load Page 1 into a browser:

  1. Page 1 creates the showMessage() function and opens a new window.

  2. Page 2 loads into the new window and calls the showMessage() function in the parent window, passing it a string value.

  3. The showMessage() function executes, displaying "Hello from Page 2!" in an alert box in Page 1.

The ability for JavaScript code to communicate between windows is pretty cool, and it can be very helpful when you are writing applications that require multiple windows. There is, however, one issue with cross-window JavaScript communication: security.

SECURITY

JavaScript's success is in part the result of its security policies, and one such policy relevant to this discussion is the same-origin policy. This states that a JavaScript script in one window can access and interact with a web page (and its JavaScript) in another window if, and only if, the web pages in both windows are from the same origin. In other words, if the pages in both windows do not come from the same domain (among finer details), JavaScript in one window cannot communicate with the web page and its JavaScript in the other window.

Two web pages or JavaScript scripts are determined to be of the same origin if the following criteria are met:

  • The protocols must match. HTTP is the primary protocol used on the Internet, and two pages or scripts must use the same protocol in order to be considered as coming from the same origin. This means http://www.wrox.com is not of the same origin as https://www.wrox.com. One URL uses the HTTP protocol, and the other uses HTTPS.

  • The host names or domain names must match. A web page's domain name is unique. In order to be considered as coming from the same origin, two pages or scripts must come from the same domain. This includes subdomains. For example, http://p2p.wrox.com is not the same domain as http://www.wrox.com. Even though the primary domain, wrox.com, is the same, the subdomains are not. Therefore, these two URLs are not considered to be from the same origin.

  • The ports must match. By default, HTTP traffic uses port 80. When you request a website, your browser uses port 80 to send the HTTP request to the server. So, the URL of http://www.wrox.com is the same as that of http://www.wrox.com:80. There are some webservers, however, that are configured to use a different port (a common one is 8080) to provide other web-based services. To be considered as having the same origin, the ports of both scripts or pages must match. This means http://www.wrox.com is not from the same origin as http://www.wrox.com:8080.

Two web pages or JavaScript scripts are considered to be from the same origin only when these three criteria are met. This means you cannot open a window to http://www.google.com and interact with its web page and JavaScript. You can change the window's size and position, and you can access the location object, but you cannot interact with any JavaScript. JavaScript's security will not allow it.

TRY IT

In this lesson, you learn about creating new windows and how to interact with them by changing their position and size, and you learn about interacting with the objects and JavaScript code (if security permits).

Lesson Requirements

For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/) or Web Matrix (www.asp.net/webmatrix/). Mac OS X users can use TextMate, which comes as part of OS X, or they can download a trial for Coda (www.panic.com/coda/). Linux users can use the built-in VIM.

You also need a modern web browser. Choose any of the following:

  • Internet Explorer 8+

  • Google Chrome

  • Firefox 3.5+

  • Apple Safari 4+

  • Opera 10+

Create a subfolder called Lesson11 in the JS24Hour folder you created in Lesson 1. Store the files you create in this lesson in the Lesson11 folder.

Step-by-Step

Write a simple web page that opens a new window with a blank page and write text to it.

  1. Open your text editor and type the following code:

    <html>
    <head>
        <title>Page 1</title>
        <script type="text/javascript">
            var childWindow = open("");
    
        </script>
    </head>
    <body>
    
    </body>
    </html>

    The JavaScript in this page opens a blank page in a new window by not specifying a URL for the window to open.

  2. Now add the bold code shown here:

    <html>
    <head>
        <title>Page 1</title>
        <script type="text/javascript">
            var childWindow = open("");
    
            childWindow.document.write("Hello, new Window!<br/>");
            childWindow.document.write("How are you today?");
        </script>
    </head>
    <body>
    
    </body>
    </html>

    This new code uses the document object's write() method to write directly into the page in the new window. The first line writes some text and an HTML <br/> element. The second line writes more text, which, when rendered in the browser, is on a second line.

  3. Save the file as lesson11_sample01.htm.

  4. Open the HTML file in your browser. You'll see a new window open, and it will contain the text written into the document.

To get the sample code files you can download Lesson 11 from the book's website at www.wrox.com.

Note

Please select Lesson 11 on the DVD to view the video that accompanies this lesson.

Step-by-Step
..................Content has been hidden....................

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