Приглашаем посетить
Чарская (charskaya.lit-info.ru)

Creating New Windows

Creating New Windows

Dynamic HTML exposes five methods on the window for creating different types of windows. These methods provide a set of predefined window types as well as custom HTML-based windows and dialog boxes.

The two styles of windows that can be created are modal and modeless. A modal window, normally a dialog box, is a window that the user must respond to before the application can continue. When a modal dialog box is displayed, the script in the original window stops and waits for the dialog box to be closed. Modeless windows are windows that operate independently of the current window; the code in modeless dialog boxes executes independently from the other windows. Using modeless windows you can create multiwindowed HTML applications.

The following table lists the methods available for creating modal and modeless windows.


Method Description
alert(message) Modal. Displays a simple modal dialog box containing a supplied message and a single OK button. The alert method should be reserved primarily for displaying error messages.
confirm(message) Modal. Similar to alert but used to ask the user a question. This dialog box displays the text along with OK and Cancel buttons. Clicking OK returns true, and clicking Cancel returns false.
open([url [, name [, features [, replace]]]]) Modeless. Opens a new instance of the browser with the specified URL. The open method allows different window features to be turned on or off.
prompt(message [, defaultText]) Modal. Displays a dialog box that requests a string from the user. The optional defaultText parameter is used to provide a default value for the text box. If the user fails to enter a string and clicks OK, an empty string is returned. If the user clicks the Cancel button or the Close box, a value of null is returned.
showModalDialog (url [, arguments [, features]]) Modal. Similar to the open method but displays a modal dialog box containing the supplied URL. The script can pass arguments into the dialog box, and because modal dialog boxes block the flow of the creating script, the dialog box can specify a return value.

The following sections discuss the use of these methods in detail.

Modeless Windows

The window object exposes an open method that lets you create a new modeless window. The new window is simply another instance of the browser; it has its own history and it navigates independently of the creating window.

The open method has the following syntax:

[windowObject =] window.open([url [, name [, features [, replace]]]])

All parameters to the open method are optional. The url parameter specifies the initial page to load. Omitting this value opens an instance of the browser with a blank document, which is useful when the document is being generated from script.

The name parameter assigns a name to the window to be used when the window is a target for subsequent documents. Targeting indicates where a document will be displayed when the user follows a link. The TARGET attribute on the anchor can specify a window name. If no window exists for a specified target, the document is displayed in a new window. If no target is specified, the new document is displayed in the current window. The name parameter, and therefore the TARGET attribute, can contain only alphanumeric characters and underscores (_).

The features parameter consists of a string that specifies the window features to display in the newly created window, thereby turning on or off the menus, toolbars, and scrollbars and specifying an initial size for the window. These features are discussed in detail in the section "Window Features" later in this chapter.

The replace parameter specifies how the new URL will be handled in its window's history list. If you omit the replace parameter or pass a value of false, the URL will be added to the end of the list as usual. If you pass a value of true, the URL will replace the current URL in the list if there is one; otherwise, it will not be added at all. The replace parameter is useful primarily for windows that have already been opened.

Manipulating the New Window

The open method returns a reference to the newly created window. By assigning the return value to a variable, you can call methods on the window later in your code. If the supplied window name refers to a window that already exists, another window with the same name is not created; rather, the new URL is displayed in the existing window. If you do not assign the return value to a variable, you cannot call the new window's methods from code. You can, however, get a reference to the window later by reopening it, as shown in the following example:

// Open a new window, but do not save a reference to it.
window.open("myPlace.htm", "myPlace");

/* Load a new document in the window "myPlace" 
   and save a reference to it. */
myPlace = window.open("myPlace2.htm", "myPlace");

This code creates only one new window instance. This technique is similar to targeting the window with a new document.

Modal and Custom HTML Dialog Boxes

As mentioned, modal dialog boxes require a response from the user before interaction with the browser can continue. The window object exposes four methods that let you prompt the user with a modal dialog box. Three methods display simple built-in dialog boxes, and the fourth method lets you create custom HTML dialog boxes. The companion CD contains a file that demonstrates how to create the different types of modal dialog boxes.

The methods for built-in dialog boxes—alert, confirm, and prompt—take message strings as arguments. In JavaScript, these strings can contain line breaks, indicated by the \n escape character. (VBScript uses chr(13) to specify line breaks.) Here is an example of a multiple-line alert message string:

alert("You entered invalid values on fields:\nName\nUser");

The showModalDialog method is used to create custom dialog boxes that can display HTML files. Inside the dialog box, the object model is slightly different from the traditional window object model because the dialog box is not a full instance of the browser, but rather a viewer for the HTML document. A modal dialog box differs from a standard browser window as follows:

Modal dialog boxes are intended for displaying messages that require a response and for requesting information from the user. Like the built-in prompt and confirm methods, custom modal dialog boxes can return information to the browser.

When you display a custom modal dialog box, you should always supply a close button. If you omit the close button, the dialog box can be dismissed only by clicking on the Close box in the upper right corner of the window. To create a close button, use the Submit button type so that the button acts as the default button. The following code creates an OK button that closes the dialog box:

<INPUT TYPE=SUBMIT VALUE="OK" STYLE="Width:5em" 
   ONCLICK="window.close();">

Displaying Custom Dialog Boxes

The first and last arguments of the showModalDialog method are essentially the same as those of the open method. The first argument specifies the URL to display, and the last argument specifies the set of window features to display. The second argument is different. Rather than take a name, the second argument can take any variable, including an array, and pass it into the dialog box. This argument allows an application to pass information into the dialog box.

You can specify a return value for the showModalDialog method by setting a special property on the dialog box. This property can take any type of variable, which is returned to the calling application.

Passing Information to and from the Dialog Box

The information passed to and returned from the dialog box is exposed in the object model of the dialog box. A copy of the variable specified as the second argument of the showModalDialog method is exposed in the dialog box as the dialogArguments property. The returnValue property is exposed for passing information back to the calling application. When the dialog box is closed, the value of this property is used as the return value for the dialog box. The following code demonstrates how to access arguments passed into and return arguments from a dialog box:

<HTML>
   <HEAD>
      <TITLE>Passing Variables</TITLE>
   </HEAD>
   <!-- When the dialog box is unloaded, 
        the value in the text box is returned. -->
   <BODY ONUNLOAD="window.returnValue = document.all.ret.value;">
      <P>You passed in the following value:</P>
      <P ALIGN=CENTER>
      <SCRIPT LANGUAGE="JavaScript">
         document.write(window.dialogArguments);
      </SCRIPT>
      <P>Enter a value to return to the application:</P>
      <P ALIGN=CENTER>
      <INPUT TYPE=TEXT ID="ret" VALUE="Return">
      <INPUT STYLE="width:5em" TYPE=SUBMIT VALUE="OK"
         ONCLICK="window.close()">
   </BODY>
</HTML>

This dialog box could be invoked using the following command:

showModalDialog("pass.htm", "Pass this string to the dialog box.");

Creating an About Dialog Box

With the alert method, you can create a simple About dialog box. With the showModalDialog method, you can create an HTML-enhanced About dialog box. The following code displays a custom About dialog box. The first document contains an About button to click to display the About dialog box.

<HTML>
   <HEAD>
      <TITLE>About Demo</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function about() {
            // Display About dialog box.
            event.srcElement.blur();
            window.showModalDialog("about.htm", "",
               "dialogWidth:25em; dialogHeight:13em")
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT TYPE=BUTTON VALUE="About" ONCLICK="about();">
   </BODY>
</HTML>

The About dialog box code is in the file about.htm:

<HTML>
   <HEAD>
      <TITLE>About Inside Dynamic HTML</TITLE>
   </HEAD>
   <BODY STYLE="text-align:center; font-size:75%;
      background:lightgrey">
      <H2>Companion CD-ROM Version 1.0</H2>
      <H3>By Scott Isaacs</H3>
      <H4 STYLE="font-style:italic">
         Demonstrating the Power of Dynamic HTML!
      </H4>
      <!-- Submit button is the default button. --> 
      <INPUT TYPE=SUBMIT STYLE="Width:5em" VALUE="OK"
         ONCLICK="window.close()">
   </BODY>
</HTML>

Creating Custom Input Dialog Boxes

The prompt method is useful for requesting simple information from the user. However, if multiple pieces of information are required, the prompt method is not sufficient. To pass multiple values back and forth between the dialog box and the creating window, you can use an array or an object. The following code demonstrates how to request multiple fields of information and pass the information back to the application:

<HTML>
   <HEAD>
      <TITLE>User Information</TITLE>
      <STYLE TYPE="text/css">
         BODY {margin-left:10pt; background:menu}
      </STYLE>
      <SCRIPT LANGUAGE="JavaScript">
         function saveValues() {
            // Build an array of return values.
            var retVal = new Array;
            for (var intLoop = 0; intLoop < document.UserInfo.length; 
                  intLoop++) 
               with (document.UserInfo[intLoop]) 
                  if (name != "") 
                     retVal[name] = value; 
            window.returnValue = retVal;
            event.returnValue = false;
            window.close();
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <!-- This form is used to group the contained controls in an 
           easy-to-access array. -->
      <FORM NAME="UserInfo">
         <FIELDSET>
            <LEGEND>User Information</LEGEND>
            <P>User Name: <INPUT TYPE=TEXT NAME="User">
            <P>Address: <TEXTAREA ROWS="3" NAME="Address"></TEXTAREA>
         </FIELDSET>
      </FORM>
      <P STYLE="text-align:center">
      <INPUT TYPE=SUBMIT STYLE="width:5em" ONCLICK="saveValues();"
         VALUE="OK">
      <INPUT TYPE=RESET ONCLICK="window.close();" VALUE="Cancel">
   </BODY>
</HTML>

If the preceding code is in a file named UserInfo.htm, the following script will display the code in a modal dialog box and then loop through and report the return values:

<SCRIPT LANGUAGE="JavaScript">
   var vals = new Array();
   vals = window.showModalDialog("UserInfo.htm");
   if (vals != null) {
      strOut = "Returned values:";
      for (name in vals)
         strOut += "\n" + name + " = " + vals[name];
      alert(strOut);
   }
</SCRIPT>

The companion CD contains a complete set of these modal dialog box examples, listed together to allow easy comparison of the different dialog box types.

Size and Position of the Dialog Box

The size and position of the dialog box are exposed as four properties of the dialog box's window:

These properties are specified in pixels and are read/write. In no case can the dialog box be sized smaller than 100-by-100 pixels or positioned off screen.

Creating Browsable Modal Dialog Boxes

A technique that can be used to work around the limitation that modal dialog boxes cannot be navigated is to display a quasidocument containing an IFrame element that references the real document to be displayed. The IFrame element creates a full instance of a browser. While this technique works, it should be used cautiously. It is not the purpose of a modal dialog box to permit the user to navigate out into the Web.

Window Features

When creating a new window using the open or showModalDialog method, you can specify a set of window features using the optional third parameter, features. The features string is a delimited list of values that turn on or off different aspects of the window. These values control the visual appearance of the window. The following two tables list the features available for these two methods.

The following features are available to the window.open method.


Feature Values Description
directories [yes|no]|[1|0] Displays a directories bar that provides quick links to various Web pages
height pixels Indicates the initial height of the browser window
left pixels Indicates the distance between the browser window and the left edge of the desktop
location [yes|no]|[1|0] Displays the address bar
menubar [yes|no]|[1|0] Displays the default menus (custom menus cannot currently be defined)
resizable [yes|no]|[1|0] Indicates whether the window is resizeable
scrollbars [yes|no]|[1|0] Displays the scrollbars for the document
status [yes|no]|[1|0] Displays the status bar at the bottom of the screen
toolbar [yes|no]|[1|0] Displays the toolbar
top pixels Indicates the distance between the browser window and the top of the desktop
width pixels Indicates the initial width of the browser window

The window.showModalDialog method supports a slightly different set of features for customizing the modal dialog box.


Feature Values Description
border [thick|thin] Specifies the thickness of the dialog box border
center [yes|no]|[1|0] Centers the dialog box
dialogHeight CSS measurement Indicates the initial height of the dialog box
dialogLeft CSS measurement CSS Indicates the left position of the dialog box
dialogTop CSS measurement Indicates the top position of the dialog box
dialogWidth CSS measurement Indicates the initial width of the dialog box
font CSS font Defines the default font for the dialog box
font-family CSS font-family Defines the default typeface for the dialog box
font-size CSS font-size Defines the default font size for the dialog box
font-style CSS font-style Defines the default font style for the dialog box
font-variant CSS font-variant Defines the default font variant for the dialog box
font-weight CSS font-weight Defines the default font weight for the dialog box
help [yes|no]|[1|0] Specifies whether to display a help icon on the title bar
maximize [yes|no]|[1|0] Specifies whether to display a maximize window button on the title bar
minimize [yes|no]|[1|0] Specifies whether to display a minimize window button on the title bar

Figure 5-1 illustrates some of the features available when you create a window using the open method.

Creating New Windows

Figure 5-1. Optional features of a window created using the open method.

The features String

Specifying a semicolon-delimited list of feature-value pairs creates the features string:

"[feature = value [; feature2 = value2… [; featuren = valuen]]]"

To create a window that does not display several of the browser features, use the following code:

window.open("example.htm", "example",
   "toolbar=no; location=no; menubar=no; status=no; directories=no");

For features that can be enabled or disabled, you can specify yes or no or 1 or 0, or simply supply the parameter to turn on the feature. For example, all of the following statements turn on the menubar feature:

window.open("...", "...", "menubar=yes");
window.open("...", "...", "menubar=1");
window.open("...", "...", "menubar");


NOTE: If compatibility with existing browsers is required, use a comma-delimited list for the open method's features string. Semicolons are supported only by Internet Explorer 4.0.

Default Values

If you create a window with the open method but provide no features string, a default set of features is automatically provided. If you provide a features string that does not specify all of the features, unspecified features don't use the same defaults; rather, they use the settings on the original window. The showModalDialog method does not support any of the browser features such as toolbars and menu bars because the modal dialog box itself is not an instance of the browser. By default, modal dialog boxes are displayed with only a title bar, a status bar, a Close box, and a help icon.

Modal Dialog Box Features and CSS

Many of the features for the modal dialog box are closely related to CSS properties. This relationship is possible because a modal dialog box, unlike a modeless browser window, displays a single document that cannot be navigated.

The font, font-size, font-weight, font-family, font-variant, and font-style properties support the same values as the CSS properties of the same names. These properties and the dialog box position and size properties correspond directly to style sheet properties, and their values can be overridden by the document's style sheet.

For example, the size of the dialog box can be specified either by the page calling showModalDialog or by the HTML document displayed in the dialog box. The page calling showModalDialog can use the features string to specify the size. The HTML document displayed in the dialog box can specify the size using the CSS width and height properties. This size overrides any size specified by the showModalDialog method. To create a dialog box that specifies its own size as 10-by-10 ems, use the style sheet shown in the following HTML page:

<HTML>
   <HEAD>
      <TITLE>10-by-10-Em Dialog Box</TITLE>
      <STYLE TYPE="text/css">
         HTML {width:10em; height:10em}
      </STYLE>
   </HEAD>
   <BODY>
      This example creates a 10-by-10-em dialog box. Ems are a
      relative unit that adapts well to different font sizes.
   </BODY>
</HTML>

The opener Property

When a window creates another window, the second window can access the first through its opener property. This property is read/write in Internet Explorer 4.0 and can be reassigned to another top-level window. This property was read-only in Internet Explorer 3.0. The opener property is useful for calling methods exposed by the window that created the new browser instance.

Closing a Window

Windows created using code can be closed using the object model. For security reasons, the user will be prompted if the code attempts to close the initial browser window. The close method is used to close the associated window:

window.close();  // Close the current window.

A user might close one window that is accessed or manipulated by a script in another window. For that reason, a closed window is not entirely destroyed; its closed property is still accessible to the user and to scripts. When you write code for one window that uses properties or methods of a second window, you should first check whether the second window still exists, as shown here:

// Check whether myWindow is closed.
if (!myWindow.closed) {
   // Code that executes if the window is open
}
else {
   // Error handler code if necessary
}

Creating a Window Manager

When a document in a browser creates another window, the only reference to the window is the variable returned by the open method. The object model does not expose a collection of open windows. Such a collection would be useful, for example, if you wanted to query for the existence of a particular window or to change the URL of a window.

The following code shows you how to implement your own windows collection containing references to all the windows your document has opened. This collection is analogous to the window's frames collection, which is discussed in the next section. However, due to the way variables work, the windows collection is accessible only for the lifetime of the document and is automatically cleared when the user navigates away from the page.

The code defines a method named createWindow that opens a window and adds a reference to it in the windows collection. Through this collection, you can query whether a window is open, change the contents, or close the window. When the document is unloaded, all windows created using createWindow are automatically closed.

<HTML>
   <HEAD>
      <TITLE>Window Manager</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         // Create an array to hold references to the child windows.
         /* Each member of this array will be a window object created
            using the createWindow method below. */
         var windows = new Array();

         function newWindow(url, wname) {
            // Constructor for the window
            /* This function should be called only by the createWindow
               function below. */
            var features = "";
            if (null != arguments[2])
               features = arguments[2];
            return window.open(url, wname, features);
         }

         function createWindow(url, wname) {
            // Add a window to the windows collection.
            var features = arguments[2] == null ? "" : arguments[2];
            windows[wname] = new newWindow(url, wname, features);
         }

         function closeWindows() {
            // Close all windows opened by addWindow.
            /* To close an individual window,
               its close method is called. */
            /* This function should be called during the onunload
               event to automatically close all open windows. */
            for (w in windows)
               if (!windows[w].closed)
                  windows[w].close();
         }

         /* The following two functions demonstrate using the
            createWindow and closeWindows methods. */

         function listWindows() {
            // List the windows and their current states.
            var swin = "Window List\n";
            for (w in windows)
               swin += w + ":" +
                  ((windows[w].closed) ? "Closed" : "Open") + "\n";
            alert(swin);
         }

         function openSampleWindows() {
            // Open two windows.
            createWindow("closeme.htm", "ChildWindow1");
            createWindow("closeme.htm", "ChildWindow2");
         }
      </SCRIPT>
   </HEAD>
   <BODY ONUNLOAD="closeWindows();">
      <H1>Window Manager</H1>
      <FORM>
         <INPUT TYPE=BUTTON ONCLICK="openSampleWindows();"
            VALUE="Add Windows">
         <INPUT TYPE=BUTTON ONCLICK="listWindows();"
            VALUE="List Windows">
         <INPUT TYPE=BUTTON ONCLICK="closeWindows();"
            VALUE="Close Windows">
      </FORM>
   </BODY>
</HTML>

This window manager works well for named windows. If you create several windows using the createWindow method but pass empty strings for their names, the window manager will lose track of all but the most recently created window.

[Содержание]