| JavaScript - Multiple windows and frames | | Print | |
Multiple windows and frames
As discussed previously, the open( ) method of the Window object allows you to create new browser windows that are represented by new Window objects. The window that a script is running in is the global object for that script, and you can use all the properties and methods of that Window object as if they were globally defined. When a script running in one window needs to control or interact with a different window, however, you must explicitly specify the Window object:
// Create a new window and manipulate it
var w = open("newdoc.html");
w.alert("Hello new window");
w.setInterval("scrollBy(0,1)",50);
HTML allows a single window to have multiple frames. Many web designers choose to avoid frames, but they are still in fairly common use. JavaScript treats each frame as a separate Window object, and scripts in different frames run independently of each other. The frames property of the Window object is an array of Window objects, representing the subframes of a window:
// Scripts in framesets refer to frames like this:
frames[0].location = "frame1.html";
frames[1].location = "frame2.html";
// With deeply nested frames, you can use:
frames[1].frames[2].location = "frame2.3.html";
// Code in a frame refers to the top-level window:
top.status = "Hello from the frame";
The parent property of a Window object refers to the containing frame or window. The top property refers to the top-level browser window that is at the root of the frame hierarchy. (If the Window object represents a top-level window rather than a frame, the parent and top properties simply refer to the Window object itself.)
Each browser window and frame has a separate JavaScript execution context, and in each context, the Window object is the global object. This means that any variables declared or functions defined by scripts in the window or frame become properties of the corresponding Window object. This allows a script in one window or frame to use variables and functions defined in another window or frame. It is common, for example, to define functions in the <head> of a top-level window, and then have scripts and event handlers in nested frames call those functions using the top property:
// Code in a frame calls code in the top-level window.
top.stop_scrolling();
| Users' Comments (0) |
|
No comment posted






