Elevation 8th BOM 8.1window Object

Source: Internet
Author: User
Tags time in milliseconds

8.1 Window Object

The core object of the BOM is window, which represents an instance of the browser. In the browser, window is an interface through JavaScript that accesses the browser window and is the global object specified by ECMAScript. This means that any object defined in the Web page, Variables and functions, both with window as their global object, have access to methods such as parseint ().

8.1.1 Global scope

All variables declared in the global use domain will become properties and methods of the Window object.

var age=29;     function Sayage () {        Console.log (this. Age);    }    Console.log (window.age); //  in    Sayage (); //  in    Window.sayage (); //  in

Because Sayage () exists in the global scope, This.age is mapped to window.age.

There is a little difference between defining a global variable and defining it directly on the Window object: The global variable cannot be deleted by the delete operator, and the properties defined directly on the Window object can.

var age=29;    Window.color= "Red";     // throws an error on ie<9 and returns false    in all other browsers Delete window.age;     // throws an error when ie<9, returns True    in all other browsers Delete Window.color;    Console.log (window.age); //  in    Console.log (Window.color); // undefined

The above uses the VAR statement to add to the Window property has an attribute named [[Configurable]], the value of which is set to false, so the defined properties can not be deleted by the delete operator.

IE8 and earlier when you encounter a statement that uses Delete to delete the Window property, it throws an error, regardless of how the property was originally created, as a warning. IE9 and later versions do not throw errors.

Note: Attempting to access an undeclared variable throws an error, but by querying the Window object, you can know if a variable that might not be declared exists.

// there will be an error    . var newvalue=oldvalue; // uncaught referenceerror:oldvalue is not defined    // There is no error, because this is a property query    var newvalue=Window.oldvalue;    Console.log (newvalue); // undefined

The Windows Mobile platform's IE browser does not allow the creation of new properties or methods directly on the Window object in the form of window.property=value. However, all the variables and functions declared in the global scope It becomes a member of the Window object.

8.1.2 Window Relationship and framework

If the page contains frames, each frame has its own window object and is saved in the Frames collection.

Each Window object has a Name property that contains the names of the frames.

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Document</title></Head><Framesetrows= "160,*">    <Framesrc= "Frame.htm"name= "Topframe">    <Framesetcols= "50%,50%">        <Framesrc= "Anotherframe.htm"name= "Leftframe">                </Frame>        <Framesrc= "Yetanotherframe.htm"name= "Rightframe">                    </Frame>    </Frameset></Frameset></HTML>

The above code creates a frameset, where one frame is in the top two frames. For this example, you can refer to the frame above by window.frames[0] or window.farmes["Topframe".

The top object always points to the highest (most outer) layer of the frame, which is the browser window.

For any code written in a framework, the window object points to a specific instance of that frame, not the top-level frame.

The other window object that is relative to top is parent. As the name implies, the parent object always points to the immediate upper frame of the current frame.

In some cases, the parent may be equal to top, but in the absence of a frame, the parent must be equal to top (at which point they are equal to window).

Note that unless the top-level window is opened through window.open (), the Name property of its window object will not contain any values.

The last object associated with the framework is self, which always points to the window; the Selft and window objects are actually used interchangeably. The purpose of introducing the Self object is only to correspond to the top and parent objects, so it does not contain additional values.

All of these objects are properties of the Window object and can be accessed in the form of window.parent,window.top. At the same time, this also means that different levels of window objects can be concatenating up, For example Window.parent.parent.frames[0].

In the case of frames, there are multiple global objects in the browser. The global variables defined in each frame automatically become properties of the Window object in the frame. Because each Window object contains a constructor of the native type, each frame has its own constructor, These constructor one by one correspond, but are not equal. For example, top. object is not equal to top.frames[0]. Object.

8.1.3 Window Position

Both Ie,safari,opera and Chrome provide Screenleft and Screentop properties, each representing the position of the window relative to the left and top of the screen.

These two properties are also supported in FF for Screenx and Screeny,safari and Chrome. Opera supports but does not correspond.

Use the following code to get the left and top positions of the window across the browser.

var leftpos= (typeof window.screenleft== "number")? Window.screenLeft:window.screenX;     var toppos= (typeof window.screentop== "number")? Window.screenTop:window.screenY;

There are a lot of compatibility issues between browsers, and you need to pay more attention.

8.1.4 Window Size

Ie9+,ff,safari,opera,chrome provides 4 properties for determining the size of a window: Innerwidth,innerheight,outerwidth,outerheight.

Each browser has a different value for the property, and it needs to be practiced on each browser.

Although it is not possible to determine the size of the browser window itself at the end, the size of the page viewport can be obtained.

var pagewidth=window.innerwidth;     var pageheight=window.innerheight;     if (typeof pagewidth!= "number") {        if(document.compatmode== "Css1compat") {            pagewidth=document.documentElement.clientWidth;            PageHeight=document.documentElement.clientHeight;        } Else {            PageWidth=document.body.clientWidth;            PageHeight=document.body.clientHeight;        }    }

8.1.5 Navigating and opening windows

Use the window.open () method to navigate to a specific URL or to open a new browser window. This method can receive 4 parameters: the URL to load, the window target, An attribute string and a Boolean value that indicates whether the new page supersedes the currently loaded page in the browser history. Usually only the first argument is passed, and the last parameter is only used without opening a new window.

If the second argument is passed for window.open (), and the parameter is the name of an existing window or frame, the URL specified by the first parameter is loaded in the window or frame that has that name.

// equals to <a href= "http://www.baidu.com" target= "Topframe" ></a>window.open ("http://www.baidu.com/" , "Topframe");

The second parameter can also be either _self,_parent,_top or _blank.

1. Pop-up windows

The second parameter in window.open () is not a window or frame that already exists, and the method creates a new window or a new tab based on the character passed in at the third parameter position. If there is no third argument, a full default setting (toolbar, address bar, status bar, etc.) is opened new browser window (or open a new tab-depending on your browser settings). The third parameter is ignored when a new window is not opened.

The third parameter is a comma-delimited set string that indicates which attributes are displayed in the new window.

Set up Value Description
Fullscreen Yes or no Indicates whether the browser window is maximized. IE only
Height Numerical Represents the height of the new window. cannot be less than 100
Left Numerical Represents the left coordinate of a new window. cannot be negative
Location Yes or no Indicates whether the address bar is displayed in a browser window. The default values for different browsers are different. If set to No, the address bar may be hidden or may be disabled (depending on the browser)
MenuBar Yes or no Indicates whether the menu bar is displayed in a browser window. Default to No
Resizable Yes or no Indicates whether the size of the browser window can be changed by dragging its border. Default value is no
Scrollbas Yes or no Indicates whether scrolling is allowed if the content does not appear in the viewport. Default value is no
Status Yes or no Indicates whether the status bar is displayed in a browser window. Default value is no
Toolbar Yes or no Indicates whether the toolbar is displayed in a browser window. Default value is no
Top Numerical Represents the top coordinate of a new window. cannot be negative
Width Numerical Represents the width of the new window. cannot be less than 100

Some or all of the setting options listed in the table can be specified by a comma-separated list of name values. Where the name value pairs are represented by an equal sign (note that spaces are not allowed in the entire attribute character).

window.open ("http://www.baidu.com", "Baiduwindow", "Height=400,width=400,top=10,left=10,resizable=yes");

The window.open () method returns a reference to the new window.

var baiduwin=window.open ("http://www.baidu.com", "Baiduwindow", "height=400,width=400,top=10,left=10, Resizable=yes "); // Sizing Baiduwin.resizeto (500,500); // Moving position baiduwin.moveto (100,100);

Calling the Close () method also closes the newly opened window. However, this method only applies to pop-up windows that are open through window.open ().

For the main window of the browser, it cannot be closed without the user's permission. However, pop-ups can call Top.close () to close itself without the user's permission. After the pop-up window closes, the window's reference is still there, but in addition to detecting its closed property, No other use has been made.

Baiduwin.close (); alert (baiduwin.closed)

However, the results are not the same as those detected in multiple browsers.

The newly created Window object has a opener property that holds the original window object that opened it. This property is defined only in the outermost window object (top) of the popup, and points to the window or frame that calls window.open ().

var baiduwin=window.open ("http://www.baidu.com", "Baiduwindow", "height=400,width=400,top=10,left=10, Resizable=yes "); alert (Baiduwin.opener==window); // true

In Chrome, the opener property of the newly created tab page is set to NULL, which means that a new tab is run in a separate process.

var baiduwin=window.open ("http://www.baidu.com", "Baiduwindow", "height=400,width=400,top=10,left=10, Resizable=yes "); Baiduwin.opener=null;

Setting the opener property to Null tells the browser that the newly created tab page does not need to communicate with the tab that opens it, so it can run in a separate process. Contact between tabs once cut off, there will be no way to recover.

2. Security restrictions

IE6 does not allow pop-ups to be created outside the screen, does not allow pop-ups to be moved outside the screen, does not allow the status bar to be closed, and so on. IE7 adds more security restrictions, such as not allowing the address bar to be closed, and by default, does not allow you to move or resize the pop-up window. FF1 does not support modifying the status bar from the outset, so the status bar is displayed without exception in the pop-up window, regardless of the character string passed to window.open (). Later, FF3 forces the address bar to always appear in the pop-up window. Opera only opens the pop-up window in the main browser window, They are not allowed to be confused with the System dialog box.

3. Pop-up screen blocker

There are two possibilities to consider when a pop-up window is blocked. window.open () is likely to return NULL if it is a pop-up that is blocked by the browser's built-in masking program.

At this point, you can determine whether the pop-up window is masked if the returned value is detected.

var baiduwin=window.open ("http://www.baidu.com", "Baiduwindow", "height=400,width=400,top=10,left=10, Resizable=yes "); if (baiduwin==null) {    alert ("The Popup was blocked!" );}

window.open () usually throws an error if it is a browser extension or a pop-up that is blocked by another program. Therefore, in order to accurately detect whether the pop-up window is masked, the return value must be detected at the same time, the window.open () The call is encapsulated in a try-catch block.

var blocked=false; Try {    var baiduwin=window.open ("http://www.baidu.com", "Baiduwindow", "height=400,width=400,top =10,left=10,resizable=yes ");     if (baiduwin==null) {        blocked=true;    }} Catch (ex) {    blocked=true;} if (blocked) {    alert ("The Popup was blocked!" );}

8.1.6 intermittent calls and timeout calls

JavaScript is a single-threaded language, but it allows you to schedule code to execute at a specific time by setting a time-out value and an interval.

The former executes the code after the specified time, which executes the code once every specified time.

The timeout call needs to use the settimeout () method of the Window object, which accepts two parameters: the code to execute and the time in milliseconds (that is, how many milliseconds to wait before executing the code).

The first parameter can be a string that contains the JS code (not recommended) and can only be a function, the second argument is a number of milliseconds to wait, but the code specified after that time is not necessarily executed. Because JS is single-threaded, the executed code has a task queue, They are added sequentially. If the queue is empty, the added code executes immediately, and if it is not empty, it waits until the code in front of it executes.

After calling SetTimeout (), the method returns a numeric ID that represents the timeout call. This timeout call ID is a unique identifier for the plan execution code that can be used to cancel the timeout call. To cancel a time-out call plan that has not yet been executed, you can call Cleartimeout () Method and pass the corresponding timeout call ID as an argument to it.

The code for the timeout call is executed in the global scope, so the value of this in the function points to the window object in non-strict mode, which is undefined in strict mode.

An intermittent call is similar to a timeout call except that it repeats the code at the specified interval until the intermittent call is canceled or the page is sanctioned.

In a development environment, a real intermittent call is seldom used because the latter intermittent call may be started before the end of the previous intermittent call.

8.1.7 System dialog box

The browser can use the alert (), confirm (), prompt () method to invoke the System dialog box to display the information to the user. The System dialog box does not have a relationship with the Web page that is displayed in the browser, nor does it include HTML. The code that displays these dialog boxes stops executing, The code resumes execution when the dialog box is closed.

Alert () Warning dialog box

Confirm () Confirmation dialog box

In order to determine whether the user clicked confirm () OK or Cancel, the Boolean value returned by the Confirm () method can be detected: True to click Ok,false to click Cancel.

Prompt () hint box, which prompts the user to enter some text

Elevation 8th BOM 8.1window Object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.