Export (0) Print
Expand All

Working with Windows, Frames, and Dialog Boxes

Note  As of December 2011, this article has been archived and is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Windows Internet Explorer, see Internet Explorer Developer Center.

Internet Explorer creates a window object whenever it opens an HTML document. Because this object is the highest-level object in the object model, you use it to gain access to properties and subobjects in the object model that you need to dynamically access the document content. This article explains how to use the window object, create new window objects, and create special types of window objects.

For information about cross-window and frame scripting issues, see About Cross-Frame Scripting and Security. Security considerations limit the cross-window access from scripts, and reading this section will help you understand what you can and cannot do through scripting.

Using the Window Object

The window object is the root of the object hierarchy. All properties in the object model are either accessed as properties of the window object or as properties of those properties. For example, you access the document through the document property of the window object. Properties that have properties are often called objects or subobjects, so document is referred to as the document object. For a complete list of the window object's properties, see DHTML Properties.

Because the current window object is implied, you do not need to prefix the property with the window keyword. However, many people prefer to use the keyword to ensure that their scripts are as clear and readable as possible. For example:


status = "hello";

is the same as saying:


window.status = "hello";

and both will work when referring to the current window object.

Many of the properties of the window object can be used to carry out simple tasks, such as displaying messages, prompting for input, and loading new documents into the window. For example, you can display a simple modal message box from the current window using the alert method, then and changing the text in the Internet Explorer status bar using the status property, as in the following example.



<html>
<head><title>A Simple Document</title>
<script language="javascript">
function doAlert() {
    window.status = "Page is loaded!";
    alert("Page is loaded!");
}
</script>
</head>
<body onload="doAlert()">
<p>This is a very short document.</p>
</body>
</html>

Click to view sample.

You can use the navigate method or the location object to load a new document into a window. This action is similar to the user clicking a link to the new document, but it can be carried out from script. The following example uses the navigate method to load the new document, named sample.htm, after a 60-second timer (using the setTimeout method) elapses.


window.setTimeout("window.navigate('sample.htm')", 60000);

You can also use the location object to navigate within the current document. For example, the following statement jumps to the anchor named "sample".


window.location.hash="#sample";

There can be more than one window object at a time. For example, the browser creates one window object for each frame defined within a document. From the scripting perspective, the current window object is always the one that contains the document that contains the script. To access window objects other than the current window object, precede the property with a window reference. The window.open method returns a reference to this new window, which is then used in scripts to access properties and methods of the new window.

The following example uses the method to open a window and load "sample.htm" when the user clicks the button.



<html>
<head><title>Creating a Window</title>
<script>
function fnOpen(){
   var mysample=window.open('sample.htm');
}
</script>
</head>
<body>
<p><button onclick="fnOpen()">Open Sample</button></p>
</body>
</html>

Click to view sample.

The new window is a separate instance of Internet Explorer, and the window object created for it is different than that of the original window. The new window can be referenced from the current window in script using the name "mysample". The following example creates a new window for "sample.htm", and then assigns the title of the new window's document to the status bar of the original window.



var new_window = window.open("sample.htm");
if (new_window != null) 
    window.status = new_window.document.title;

Click to view sample.

Once a window creates another window, it can manage that window in a variety of ways, from loading new documents in the window using the navigate method or location object, to closing the window using the close method. Closing the window unloads the document and closes the separate instance of Internet Explorer.

Because the user can also close the new window at any time, you should make sure that the window exists before attempting to access it. You can do this by checking the closed property, which is set to true when the window is closed.

You can assign a name to a window when you create it using the optional second parameter of the open method. The name is useful as the target of a link, causing the document specified by the link to load in the window. The following document creates a window named "Sample". The links later in the document use "Sample" as the target name.



<html>
<head><title>Linking to Sample</title>
</head>
<body onload="window.open('sample.htm','Sample')">
<p>Click the following links to view the documents in the Sample window:</p>
<p><a href="abc.htm" target="Sample">All About Abc</a></p>
<p><a href="xyz.htm" target="Sample">Some Words on Xyz</a></p>
</body>
</html>

Click to view sample.

By default, the open method creates a window that has a default width and height and the standard menu, toolbar, and other features of Internet Explorer. You can alter this set of features by using the optional third parameter. This parameter is a string consisting of one or more feature settings, including settings for the position and dimension of the window. The example following creates a 200-by-400-pixel window that has a status bar, but does not have a toolbar, menu bar, or address field.



window.open("sample.htm",null,
    "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");

For more information about the window features, see the open method.

Creating and Using Frames

Frames are a way to organize and structure HTML documents, creating compound views that the user sees within the main window of Internet Explorer. Each frame is itself a unique window within the main window. To access the frame's content, use the window object.

To create frames, use the iframe element or the frameSet and frame elements. Each element creates a frame and loads a specified document. The following example creates two equally sized rectangular frames that fill the main window.



<html>
  <head><title>Two Equal Frames</title>
</head>
<frameset cols="50%,*">
  <frame src=x.htm>
  <frame src=y.htm>
</frameset>
</html>

In a document within a frame, such as the "x.htm" and "y.htm" documents in the preceding example, you can use the window object as you would in a document within the main window. This means you can obtain access to the document and event objects for the frameset document and write script that will run from this frameset document. If you use script or need to instantiate an object from this frameset document, you need to define these in the head section. A BODY element is mutually exclusive from a frameSet. Using both in a single document will result in the first one being instantiated and the second one ignored. Many authors try to use a BODY element to set the background color and then instantiate a frameSet. Microsoft Internet Explorer 4.0 will instantiate the BODY and ignore the frameSet. Move the background color settings to the frameSet, and remove the BODY from this document. The browser will then instantiate the frameSet as you would expect.

You can also gain access to the window that created the frame, called the parent window, and to the other frames created by the parent by using the parent property and the frames collection. The following Microsoft JScript example uses the parent property of the frames collection to display the URL of the documents in each frame.


for (i=0; i<window.parent.frames.length; i++) 
    alert("Frame #" + i + " contains: " + window.parent.frames(i).location);

The frames collection contains window objects for each frame, so you can use the same properties and methods with these objects as you would within the current window. For example, you can gain access to the complete contents of the document in another frame using the frames collection to display the title of each document, as in the following example.


for (i=0; i<window.parent.frames.length; i++) 
    alert("The title of frame #" + i + " is: " + window.parent.frames(i).document.title);

Note  Cross-frame security limits scripting to documents loaded from the same domain. Use the domain property to determine and/or set the domain of a document. For more information about cross-frame security and scripting considerations, see About Cross-Frame Scripting and Security.

The frames collection also works this way for the document object. In this case, the frames collection from the document contains window objects for all frames created by iframe elements in a document. Consider the following example.


<html>
<head><title>Two Floating Frames</title>
<script>
function showFrames() {
    for (i=0; i<window.document.frames.length; i++) 
        alert("The title of frame #" + i + " is: " + 
            window.document.frames(i).document.title);
}
</script>
</head>
<body onload="showFrames()">
<iframe src="x.htm" align=left></iframe> Here's some text to the right of a frame.
<br clear="left"/>Here's some text beneath the frame.
<br />
<iframe src="y.htm" align="right"></iframe> Here's some text to the left of a frame.
<br clear="right" />Here's some text beneath the frame.
</body>
</html>

Click to view sample.

The preceding example contains two floating frames, one aligned to the left and the other to the right. Once the document is loaded, the showFrames function uses the frames collection to access each frame and display the title of the corresponding document.

Unlike windows created using the open method, you cannot close the window associated with a frame. The frame is "closed" when the window that created it is unloaded. Also, properties that apply to the main window, such as status, have no purpose within a frame. Frames do not have status bars, so attempting to get or set the status property has no effect for the individual frames, and you should access the parent frameset document to set the status bar.

Accessing the window object associated with a frame is not the same as accessing the frame or iframe element that created the frame. In particular, you cannot access the attributes of these elements using the window object. Instead, you must use the object for the element, which you can get from the all collection for the document that contains the frame element. For example, if you want to remove the scroll bars from a frame, you have to set the scrolling property of the iframe element as follows:


document.all.tags("IFRAME").item(1).scrolling="no";

For more information about element objects and their properties, see Scripting with Elements and Collections.

Creating and Using Modal Dialog Boxes

A dialog box is a special window that you create using the showModalDialog method on the window object. Dialog boxes are useful for soliciting input from the user in a way that does not obscure the information in the current window. They are also useful for displaying important information that the user should act upon or acknowledge before proceeding.

The showModalDialog method is similar to the open method in that it takes the URL of an HTML document and displays the document in a new window. One of the main differences, however, is that the dialog box is modal, meaning it does not release the input focus until it is closed. This means the user cannot switch back to the window that created the dialog box until the dialog box is closed. However, this does not prevent the user from switching to other windows or applications.

You typically create dialog boxes in response to user input, such as clicking a button or choosing an item in a menu. The following example calls the showModalDialog method directly from the onclick attribute of a button element.


<button onclick="window.showModalDialog('dialog.htm')">Search</button>

The showModalDialog method used in the preceding example creates a dialog box with standard size and features, and loads the document dialog.htm into the new window.

You can load any valid HTML document into a dialog box, but most dialog documents contain one or more controls with which the user supplies input or directs an action. The following example provides a text control for letting the user specify a string to search for, and buttons to confirm or cancel the search. The string is returned to the main window by assigning it to the returnValue property.


<html>
<head><title>search for</title>
<script language="javascript">
function doOK() {
    window.returnValue = window.document.all.MySearch.value;
    window.close();
}
function doCancel() {
    window.returnValue = "";
    window.close();
}
</script>
</head>
<body>
<p><em>Search For:</em> <input id="mysearch" type="text"></p>
<center>
<button onclick="doOK()">OK</button>&nbsp;
<button onclick="doCancel()">Cancel</button>
</center>
</body>
</html>

Click to view sample.

When the preceding example is displayed, the user can type a string into the text control (identified by "MySearch") and click either the OK or Cancel buttons to carry out an action. Clicking OK calls the doOK function, which retrieves the text from the text control and assigns it to the returnValue property of the dialog box. Clicking Cancel calls the doCancel function, which assigns an empty string to the returnValue property. Both functions then call the close method to close the dialog box and return the input focus to the original window.

The returnValue property on the window object specifies the value returned by the showModalDialog method after the dialog box closes. Setting this property is one way a dialog box can return information to the original window. Assuming the document in the preceding example is in a file named search.htm, the following example can use the returned string to carry out a search.




function doSearch() {
    var str = showModalDialog("search.htm");
    if (str == "")
        return;    // user canceled search
    else {
        // search for the string
     }
}

You can pass arguments to a dialog box using the second parameter of showModalDialog. This parameter accepts any valid type, so an array can be passed just as easily as a discrete type.


var aCafeArgs = new Array("Tall", "Decaf", "Non-fat", "Mocha");
var cResult = window.showModalDialog("barista.htm", aCafeArgs);

A dialog box can retrieve the arguments through the dialogArguments property of the window object. Passing arguments is a useful way for the original window to specify the initial values for the controls in the dialog box. Consider the dialog document in the following search example. By scripting the onload event of the body element to call the following function, the dialog box can set the initial search string to a value supplied by the original window.



function doInit() {
    if (window.dialogArguments != null)
        window.document.all.MySearch.value = window.dialogArguments;
}
   .
   .
   .
<body onload="doInit()">

To set the initial search string to the words "Sample Text", the original window calls showModalDialog, as in the following example.


var str = showModalDialog("search.htm", "Sample Text");

A better way to make use of the dialog arguments for this example is to store the search string in a variable within the document of the original window, as in the following example.



var str = "";
function doSearch() {
    str = showModalDialog("search.htm", str);
    if (str == "")
        return;    // user canceled search
    else {
        // search for the string
    }
}

Storing the returned string in the global variable ensures that the previous search string is available whenever the user requests another search. Remember that stored values are discarded when a document is unloaded, so you cannot store the previous string with the dialog document. This also means that the stored string in the original window is discarded when that document is unloaded.

In addition to setting initial values, you can also set the input focus to a specific control in the dialog box using the focus method. This ensures that when the dialog document is loaded, the user can begin entering input immediately without first moving the focus to an appropriate control. The input focus is typically set in the same function that sets initial values for the dialog box. To set the focus to the text control in the preceding example, use the following:


window.document.all.MySearch.focus();

If the original window has more than one value to exchange with the dialog box, it can do this by passing an object to the dialog box as an argument. For example, the following dialog document prompts the user with both a Match Case check box and a Search For string. To receive the user's settings for these, the original window passes an object that the dialog box sets when the user clicks OK or Cancel.



<html>
<head><title>Search For</title>
<script language="javascript">
function doInit() {
    if (window.dialogArguments != null) {
        window.document.all.MySearch.value = window.dialogArguments.str;
        window.document.all.MatchCase.checked = window.dialogArguments.caseSensitive;
    }
    window.document.all.MySearch.focus();
    window.returnValue = false;
}
function doOK() {
    window.returnValue = true;
    if (window.dialogArguments != null) {
        window.dialogArguments.str = window.document.all.MySearch.value;
        window.dialogArguments.caseSensitive = 
            window.document.all.MatchCase.checked;
    }
    window.close();
}
function doCancel() {
    window.returnValue = false;
    window.close();
}
</script>
</head>
<body onload="doInit()">
<input ID="MatchCase" type="checkbox">&nbsp;<em>Match Case</em> 
<p><em>Search For:</em> <input id="MySearch" type="text"></p>
<center>
<button onclick="doOK()">OK</button>&nbsp;
<button onclick="doCancel()">Cancel</button>
</center>
</body>
</html>

Click to view sample.

Be careful! Any document that uses this dialog document needs to properly declare and initialize the object. The following example declares the myDialog object and initializes the object before calling showModalDialog.



function myDialog() {
    var str;
    var caseSensitive;
}
function doSearch() {
    myDialog.str = "";
    myDialog.caseSensitive = false;
    if (showModalDialog("search.htm", myDialog)==false)
        return;    // user canceled search
    else {
        // search for the string
    }
}

An alternate way to pass multiple values between the original window and the dialog box is to concatenate those values into a single string, and leave it to the documents to parse the string and extract the values.

You can set the appearance and size of a dialog box from the third parameter of the showModalDialog method. The following example creates a dialog box that uses a default font size of 10 pixels and a dialog box width and height of 10 ems.


window.showModalDialog("dialog.htm",null,
    "font-size:10px;dialogWidth:10em;dialogHeight:10em")

In the preceding example, the third parameter takes a string consisting of one or more settings separated by semicolons (;). Each setting consists of a name and a value separated by a colon (:) or an equal sign (=). The value depends on the ornament. If it is a number, it takes a units designator, such as px or em.

You use the dialogWidth and dialogHeight properties to set the initial width and height of the dialog box. Similarly, you can use dialogLeft and dialogTop to set the initial position of the dialog box relative to the upper-left corner of the desktop, not the parent window. If you don't want to calculate the left and top positions for the dialog box, you can center it in the desktop using the keyword center.

Although the position, width, and height of a dialog box are typically set by the parent document, you can retrieve and change these settings from within the dialog box itself using the dialogLeft, dialogTop, dialogWidth, and dialogHeight properties. Changing these settings is important, for example, if you want to expand the content of the dialog box to show additional options that the user can choose from.

You can set the default font, font size, weight, and style for text in the dialog box using the font, font-size, font-weight, and font-style properties. These properties take the same values as the Cascading Style Sheets (CSS) attributes of the same name. The default settings apply only to text in the dialog box that does not already have explicit font settings.

Showing a Help Window

You can show help files in the browser using the showHelp method on the window object. The following example creates a help window that would display an HTML help file. For HTML Help, there are no modifying parameters, and only defaults will apply to the new window.


<BUTTON onclick="window.showHelp('helpinfo.htm')">Show Help</BUTTON>

You can also use the showHelp method to display WinHelp files. To display WinHelp files, the first parameter of the showHelp method specifies an .hlp file, the second parameter specifies a context identifier, and the third (optional) parameter can be used to specify "popup". The default view for help files is to show the help file in the main browser window. If "popup" is specified for WinHelp files, the help file is displayed in a separate window.

 

 

Show:
© 2014 Microsoft