BOM (Browser object model) browser objects models

Source: Internet
Author: User
Tags blank page

The role of the object, so all variables/functions declared in the global scope become properties and methods of the Window object;/PS: Attempting to access an undeclared variable throws an error, but by querying the Window object, you can know if an object that might not be declared exists; var NewValue = OldValue; =>referenceerror:oldvalue is not defined;var newvalue = Window.oldvalue; =>undefined;

Properties and methods for 1.window objects
The Window object has a series of properties, which are also objects themselves;

(1). Properties
attribute meaning
Closed is true when the window is closed;
Defaultstatus The default status information displayed in the status bar at the bottom of the window;
The Document object currently displayed in the Documents window;
An array of frame objects in the frames window;
History saves the URL of the recently loaded window;
The number of frames in the length window;
The URL in the current window of the location;
Name Window name;
Offscreenbuffering is used to draw new window content and copy existing content after completion, control screen update;
Opener Open the window of the current window;
The parent points to a window that contains another window (used by the framework);
Screen display-related information, such as height/width (in pixels;)
Self indicates the current window;
Status describes the temporary information that is caused by user interaction;
Top contains the topmost window of a particular window (used by the framework);
Windows indicates the current window, which is equivalent to self;

(2). method
Alert (text) Creates a warning dialog box, displaying a message;
Blur () removes the focus from the window;
Clearinterval (interval) clears the timer interval set before;
Cleartimeout (timer) clears the timeout set previously;
Close () closes the window;
Confirm () Creates a dialog box that needs to be used for confirmation;
Focus () moves the focal point to the window;
Open (Url,name,[options]) opens a new window and returns to the new Windows object;
Prompt (Text,defaultinput) creates a dialog box that requires the user to enter information;
Scroll (x, Y) scrolls to the position of a pixel in the window;
SetInterval (expression,milliseconds) calculates an expression at a specified time interval;
SetInterval (Function,millisenconds,[arguments]) invokes a function after a specified time interval;
SetTimeout (expression,milliseconds) calculates an expression after the timer is exceeded;
Stetimeout (Function,milliseconds,[arguments]) calls a function after the timer is exceeded;
Print () to bring up the printing dialog box;
Find () Brings up the Lookup dialog box;
Properties and methods under window can be called using window. Properties, window. method () or direct properties, methods ();
Window.alert (text) =alert (text);

2. System dialog box
The browser uses the alert ()/confirm () and Prompt () methods to invoke the System dialog box to display the information to the user;
The System dialog box is not related to the Web page displayed in the browser, nor does it contain HTML;
Their appearance is determined by the operating system and/or browser settings, not by CSS;
These methods open the dialog boxes are synchronous and modal, that is, the display of these dialog boxes when the code will stop running, and then close the dialog box after the code will resume execution;

123456789101112131415161718192021 Pop-up Warning alert (' warning '); Confirm and Cancel if (Confirm (' OK or Cancel ') {//confirm () itself has a return value; alert (' You have selected OK ');//press OK to return a true value;}) Else{alert (' You have chosen to cancel ');//press Cancel to return false value;}//Enter the prompt box var num = prompt (' Please enter a number ', 0); The first argument is the text hint, the second parameter is the input box pattern padding value, and the value in the input box is returned; alert (num); Assigns the value returned by the prompt () method to the variable num, and pops up; Call Print and Find dialog box print (); Print Pop-up browser print window; find (); =>boolean; page has matching find content returns true, relative to ctrl+f; status bar defaultstatus = ' status bar default text '; The initial default value of the status bar at the bottom of the browser; state = ' status bar text '; The status bar at the bottom of the browser sets the value;

3. New Window (open ())

//Use the window.open () method to navigate to a specific URL, or to open a new browser window;
//It receives four parameters:
//(1). The URL to load;
(2). window's name or window target;
//(3). a specific string;
//(4). A Boolean value that indicates whether the new page supersedes the currently loaded page in the browser record;
Open (' www.baidu.com ');//chrome-search://local-ntp/www.baidu.com; open failed; http://is required;
Open (' http://www.baidu.com ');//Create new page and jump to Baidu;
Open (' http://www.baidu.com ', ' search engine ');//New page opens the Baidu page and names the window; and does not jump automatically; and just refreshes that page when it is called again;
Open (' http://www.baidu.com ', ' _parent ');//Open Baidu on this page; ' _blank ' is to specify a new page to open;
//Third string parameter
Setting value description
Width value New window, not less than 100px;
Height value of the new window, not less than 100px;
Top Value The y-coordinate of the new window, not a negative value;
The x-coordinate of the new window of left value, cannot be a negative value;
Location Boolean Displays the address bar in the browser window, and the default values for different browsers are different;
MenuBar Boolean whether the menu bar is displayed in the browser window, default to No;
Resizable Boolean to change the size by dragging the border of the browser window;
ScrollBars Boolean If the page content does not display, scroll bar is displayed; default no; The
Status Boolean displays the status bar in the browser window, default no;
Toolbar Boolean whether the toolbar is displayed in the browser, default no;
Fullscreen boolean browser window is maximized; IE support only;
Open (' http://www.baidu.com ', ' Baidu ', ' Width=400,height=400,top=200,left=200,toolbar=yes ');

The open () itself returns the Window object
var box = open (); Returns a Window object and opens a new blank page;
Box.alert ("); It then specifies that the open () returned object opens the new page of the popup window;

Word Window Operation parent window
Document.onclick = function () {//Click the Docuement object in a new window;
Opener.document.write (' child window let me output! '); /At this time the parent window generating it generates text content;
}

4. Location and size of the window

1234567891011121314 (1). The location of the window//is used to determine and modify the position of the Windows Object (browser window) relative to the screen://Ie+safari+opera+chrome both provide Screenleft and Screentop properties,// Firefox provides the Screenx and Screey properties;//They indicate the position of the window teller to the left and top of the screen respectively; Determines the position of the window =>iealert (screenleft); The distance from the screen to the left of the browser;//Determine the window's position =>firefoxalert (ScreenX); The distance from the screen to the left of the browser; Cross-browser method var leftx = (typeof screenleft = = ' number ')? screenleft:screenx;//determine whether the Screenleft is a numeric value, if the value of screenleft is used, otherwise the value of ScreenX;
12345678910111213141516171819202122232425 (2). The size of the window//detects the size of the browser window itself and the border: Outerwidth and Outerheight; Alert (outerwidth), alert (outerheight),//Detect page Size properties: Innerwidth and Innerheight;alert (innerwidth); alert (innerheight);// Ps:ie does not provide the properties of the current browser window size; There are methods available in the DOM;  //in IE and other browsers, it provides: Document.documentElement.clientWidth and Document.documentElement.clientHeight; To save the information of the page window;/PS: In IE6, the above attribute is valid in standard mode If it is a strange mode, you must use Document.body.clientWidth and document.body.clientheight;//if it is a browser such as Firefox, directly using Innerwidth and Innerheight ; var width = window.innerwidth; Add window here, because IE will not work; var height = window.innerheight;if (typeof width! = ' number ') {//IE6 browser if (Document.compatmode = = ' C Ss1compat ') {//judgment is IE6 standard mode; using Documentelement;width = Document.documentelement.clientwidth;height = Document.documentElement.clientHeight;} else{//Otherwise IE6 non-standard mode; use Body;width = Document.body.clientwidth;height = Document.body.clientHeight;}} PS: The above method can get the size of the viewable part of the browser window through different browsers;//Document.compatmode can determine whether the page is in standard mode;
1234567 Adjust the browser location; MoveTo (0,0); Move to (0,0) coordinates; IE valid; Moveby (10,10); Moving the 10px;ie down and right separately is effective; Resize Browser size resizeto (200,200); resizing; Resizeby (200,200); Expansion shrinkage size;

5. Intermittent calls and timeout calls
1//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 period.
2//timeout: Executes the code after the specified time;
3//Interval value: Executes the code once every specified time;

123456789101112 The time-out call uses the SetTimeout () method of the Window object;//It accepts two parameters: the code to execute and the number of milliseconds, and the setTimeout (function () {///directly uses the method passed in, extensibility, performance more; alert (' Warning! ');} , 1000);//After calling settimeout (), the method returns a numeric ID that represents a timeout call;//The ID of this timeout call is a unique identifier for the plan execution code, which can be used to cancel the timeout call, or cancel the time-out call plan that has not yet been executed. You can call the Cleartimeout () method and pass the corresponding time-out call ID as an argument to it; var box = SetTimeout (function () {//) assigns the ID of the timeout call to the variable Box;alert (' timeout call ');},1000); cleartimeout (box); Passing the ID into the cancel call method;
123456789101112131415161718 Intermittent invocation uses the SetInterval () method of the Window object, and/or it repeats the code at the specified interval until the intermittent call is canceled or the page is unloaded;//it receives the same parameters as settimeout (); var pox = SetInterval (function () {alert (' interval call ');},1000); Clearinterval (pox); Cancel intermittent calls; Use SetInterval () to set a 5-second timer; var num = 0; Set start second; var max = 5; Set terminating seconds; SetInterval (function () {num++;//increment num;if (num = = max) {clearinterval (this);//Cancel interval call, this means the method itself; the ID of the interval call that keeps track; Alert (' Pop-up window after 5 Seconds ');}},1000);
1234567891011121314 It is generally best to use a timeout call to simulate interval calls, and//Because the use of interval calls requires cancellation of IDs based on the situation, and may cause some problems with synchronization; The next intermittent call may start before the end of the previous intermittent call; var num = 0;var max = 5; function box () {num++;if (num = = max) {alert (' 5 Seconds after Popup ');} Else{settimeout (box,1000);//after 1 seconds to execute a timeout call;}; SetTimeout (box,1000); execution timer;/PS: When using timeout calls, it is not necessary to trace the timeout call ID, because after each execution, if another timeout call is no longer set, the call will stop automatically;

Two Location objects

Location is one of the BOM objects that provides information about the documents that are loaded in the current window, and provides some navigational functions;
In fact, the location object is the property of the Window object and the property of the Document object;
alert (location); Gets the current URL

(1). Properties of the Location object
The URL content of the property description
Hash if the part exists, it represents the anchor part;
Host hostname: port number;
hostname host name;
href entire URL;
pathname path name;
Port port number;
Protocol part of the Agreement;
Search returns the query string for the URL ('? Gws_rd=ssl#safe=strict&q=ab '), which begins with a question mark;
(2). Method of the Location object
Assign () jumps to the specified page, equivalent to the href;
Reload () overloads the current URL;
Replace () replaces the current page with a new URL;

Location.hash = ' #1 '; Set # After the string, and jump;
Location.hostname = ' Jack '; Set host name;
Location.search = '? id=5 '; Set the string after the?

12345678910111213141516171819202122 In web development, we often need to obtain key-value pairs such as Id=5&search=ok for this type of URL;//through location, we can write a function to get one by one; function Getargs () {// Create an array of key-value pairs; var args = [];//removal number; var qs = location.search.length>0?location.search.substring (1): ";//Press & String split fraction group; var items = Qs.split (' & '); var item = NULL, name = NULL, value = null;//traversal for (var i = 0; i<items.length; i++ {item = items[i].split (' = '); name = decodeURIComponent (item[0]);//Because the query string is encoded by the browser; value = decodeURIComponent (Item[1]) ;//each query string parameter becomes a property of the Args object;//The key-value pair is stored in the array; args[name] = value;} return args;} var args = Getargs (); alert (args[' id '); Gets the value corresponding to the ID in the URL, as follows:
Location.assign (' http://www.baidu.com '); Jumps to the specified url;2
Location.reload (); The most efficient reload, it is possible to load from the cache;
Location.reload (TRUE); Force load, reload from server source; 5
Locatioin.replace (' http://www.baidu.com '); On this page to jump to the Baidu page, and can avoid the history of jump to produce;

Three History objects

The history object is the property of the Window object, which holds the record of the user's Internet access, from the moment the window is opened;

(1). Properties of the History object

The number of records in the length history object;
(2). Method of the History object
Back () go to the browser history bar currently a URL, similar to backward;
Forward () go to the browser history entry next URL, similar to forward;
The Go (NUM) browser is forward or backward in the history object;

Copy the code code as follows:
function back () {
History.back ();
}
function forward () {
History.forward ();
}
function Go (num) {
History.go (num);
}
PS: Can be judged by history.length = = 0, to get a historical record;

Summary of Four

The browser object model (BOM) is based on the Window object, which represents the browser window and the visible area of the page.
The Window object is also a global object in ECMAScript, so all global variables and functions are its properties, and all native constructors and other functions exist under its namespace;
(1). Use the Location object to programmatically access the browser's navigation system, set the corresponding properties, you can modify the URL of the browser piecemeal or in a holistic manner;
(2). Call the Replace () method to navigate to a new URL that replaces the currently displayed page in the browser history;
(3). Screen object: Holds information about the client display, which is generally used only for site analysis;
(4). History object: A small gap has been opened in order to access the browser's historical record, in which the developer can judge the number of historical records, or navigate backward or forward to any page in the history record;

Two:::

What is a BOM?
    • The BOM is an abbreviation for the browser object model.
    • BOM provides an object that is independent of the content and interacts with the browser window
    • Because the BOM is primarily used to manage the communication between Windows and Windows, its core object is window
    • A BOM is composed of a series of related objects, and each object provides many methods and properties
    • BOM lack of standards, the standardization of JavaScript Grammar Organization is ECMA,DOM standardization Organization is a (whatwg,webhypertextapplicationtechnologyworkinggroup-- Web Hypertext Application Technical team is currently working to promote the standardization of the BOM)
    • The BOM was originally part of the Netscape browser standard
What can I do with the BOM?

The BOM provides some ways to access the Window object, which we can use to move the window position, change the window size, open a new window and close the window, pop up a dialog, navigate and get some information about the customer such as: Browser brand version, screen resolution. But the most powerful feature of the BOM is that it provides an entry---document object that accesses an HTML page so that we can use the powerful features of the DOM through this portal!!!

The Window object is the top-level (core) object of the BOM, all of which are extended by it or are called child objects of the window. Because window is the top-level object, you can call its child objects without displaying the indicated window object, for example, the following two lines of code are the same:

    document.write ("BOM");    Window.document.write ("BOM");

Window-the Window object is the core of all objects in the BOM. The Window object represents the entire browser window, but does not have to represent what it contains. In addition, window can be used to move or adjust the size of the browser it represents, or to have other effects on it.

Any global function or variable in JavaScript is a property of window

Window Sub-Object

    • Document Object
    • Frames Object
    • History Object
    • Location Object
    • Navigator Object
    • Screen Object

Window Object Relationship Properties

    • Parent: If the current window is a frame, point to the frame that contains the frame's window
    • Self: points to the current Window object, with window consent. (Window object)
    • Top: If the current window is frame, point to the Window object that contains the top-level of the frame
    • window: points to the current Window object, with self consent.
    • Opener: When the window is opened with JavaScript, point to the person who opened it (opener)

Window Object Positioning properties

    • IE provides window.screenleft and Window.screentop objects to determine the position of the window, but does not provide any way to determine the window size. With the Document.body.offsetWidth and Document.body. offsetheight properties, you can get the size of the viewport (the area that displays the HTML page), but they are not standard properties.
    • Mozilla provides Window.screenx and Window.screeny properties to determine the position of the window. It also provides the window.innerwidth and Window.innerheight properties to determine the size of the viewport, Window.outerwidth and Window.outerheight properties to determine the size of the browser window itself.
Method of the Window object
Form Control
moveby (x, y)-Moves the form's x pixels horizontally from the current position, moves the form y pixels vertically, X is negative, moves the form to the left, Y is negative, and moves the form up
moveTo (x, y)-Moves the upper-left corner of the form to the (x, y) point relative to the upper-left corner of the screen, and when a negative number is used as a parameter, the form moves out of the visible area of the screen
Resizeby (w,h)--relative to the current size of the form, the width adjusts to w pixels and the height of h pixels. If the argument is negative, the form is scaled down, whereas
the form
resizeto (w,h) expands--Adjusts the width of the form to w pixels and height to h pixels
Form Scroll Axis control
scrollTo (x, y)--if there is a scroll bar in the form, move the horizontal scroll bar to a position relative to the form's width of x pixels, and move the vertical scroll bar to a position relative to the form's Y-pixel height
Scrollby (x, y)-if there is a scrollbar, move the horizontal scroll bar to the position of x pixels relative to the current horizontal scroll bar (that is, move the X-pixel to the left), and move the vertical scroll bar to a position relative to the current vertical scrollbar height of y pixels (that is, move the Y-pixel down)
Form Focus Control
Focus
()--Causes the form or control to get focus
Blur ()--in contrast to the focus function, causes the form or control to lose focus
New Form
Open ()--Opens (pops up) a new form
Close
()--Close the form
Opener Property--a reference to the parent form in a new form, meaning "opener" in Chinese

Window.Open method Syntax

    window.open (URL, name, features, replace);

Open method Parameter Description

    • URL--the URL to load the form into
    • Name-a new form (destination, which will be used in the target property of the a tag to overwrite the form's contents with the name of the existing form). The Open function defaults to opening the form to the _blank pop-up of the target, so the page will open in a popup way
    • Features-a string representing the attributes of the form, with each attribute in the string separated by commas
    • Replace-A Boolean value that indicates whether the newly loaded page replaces the currently loaded page, which is usually not specified

The Open function features the parameter description and opens a new normal window if you do not use the third argument

Parameter name type Description
Height Number Set the height of the form, not less than 100
Left Number Description creates the left coordinate of the form and cannot be a negative value
Location Boolean Whether the form displays the Address bar, the default value is no
Resizable Boolean Whether the form allows resizing by dragging edges, the default value is no
ScrollBars Boolean Whether dragging is allowed inside the form when it is outside the window's visible range, the default value is no
Toolbar Boolean Whether the form displays a toolbar, the default value is no
Top Number Description creates the top coordinate of the form and cannot be a negative value
Status Boolean Whether the form displays a status bar, the default value is no
Width Number Create the width of the form, cannot be less than 100

each attribute in the attribute string is separated by commas, and no spaces are allowed between each attribute

The Open method returns a reference to the Window object for a new form

dialog box
alert (str)-pop-up message dialog box (there is a OK button in the dialog box)
confirm (str)-Popup message dialog box (contains a "OK" button and "Cancel" button)
prompt (Str,defaultvalue)-Pop-up Message dialog Box (dialog box contains a "OK" button, "Cancel" button and a text input box), due to the different browser implementation, It is also best to provide an empty string if there is no second argument (the default value in the text box)
Status bar
Window.defaultstatus Property--Changes the default display of the browser status bar (when there is no other display in the status bar), the area at the bottom of the browser is called the status bar, which is used to display information to the user
Window.status Property--temporarily changes the display of the browser status bar
Time Wait and interval function
setTimeout ()--executes the specified code after pausing the specified number of milliseconds
cleartimeout ()--cancels the code that the specified settimeout function will execute
setinterval ()--interval Specifies the number of milliseconds to execute the specified code continuously
clearinterval ()--cancels the code that the specified setinterval function will execute

The settimeout and SetInterval methods have two parameters, the first parameter can be either a string or a function reference, the second parameter is the interval of milliseconds, and their return is a numeric ID that can be used for the corresponding clear method

    var tid = setTimeout ("Alert (' 1 ')", +);    Alert (TID);    Cleartimeout (TID);

History object, navigating through browser histories

History object's properties: Length returns the number of URLs in the browser history list

Methods of the History object

    • Back () load the previous URL in the history list
    • Forward () load the next URL in the history list
    • Go (num) loads a specific page in the history list
Location Object

Properties of the Location object

    • Hash set or return the URL (anchor) starting with the pound sign (#)
    • Host sets or returns the hostname and port number of the current URL
    • Hostname Sets or returns the host name of the current URL
    • HREF Sets or returns the full URL
    • Pathname Sets or returns the path portion of the current URL
    • Port Sets or returns the port number of the current URL
    • Protocol the protocol that sets or returns the current URL
    • Search Sets or returns a URL starting from a question mark (?) (Query section)

Method of the Location object

    • Assign () loads the new document, which is the same as the HREF attribute that assigns a URL directly to the Location object.
    • Reload () reloads the current document, if the method does not specify a parameter, or if the parameter is False, it uses the HTTP header if-modified-since to detect whether the document on the server has changed. If the document has changed, reload () will download the document again. If the document does not change, the method will load the document from the cache. This is exactly the same as when the user clicks the browser's Refresh button. If the parameter of the method is set to true, it bypasses the cache and re-downloads the document from the server, regardless of the last modification date of the document. This is exactly the same as when the user presses the refresh button of the browser while holding down shift.
    • Replace () replaces the current document with a new document, and the Replace () method does not generate a new record in the history object. When you use this method, the new URL overwrites the current record in the history object.
Navigator Object

Navigator properties of an object

    • appCodeName return the code name of the browser
    • AppName returns the name of the browser
    • AppVersion returns the platform and version information of the browser
    • Browserlanguage returns the language of the current browser
    • Cookieenabled returns a Boolean value that indicates whether cookies are enabled in the browser
    • Cpuclass returns the CPU level of the browser system
    • OnLine returns a Boolean value indicating whether the system is in offline mode
    • Platform returns the operating system platform running the browser
    • Systemlanguage returns the default language used by the OS
    • UserAgent returns the value of the user-agent header of the server sent by the client
    • Userlanguage returns the natural language settings of the OS
Frame with multi-window communication child window with parent window

Only the window that is opened by itself and using the Window.Open method can be accessed by JavaScript, and the window opened by the Window.Open method accesses the parent window through the Window.opener property. In the opener window, you can access the open window by the return value of the window.open Method!

Framework

Window.frames collection: In a frameset or page containing an IFRAME tag, the Frames collection contains a reference to a window in a frame

    alert (frames.length);//The number of frames    alert (frames[0].document.body.innerhtml);//use subscript directly to get a reference to the window in the frame    //Not only can use subscript, You can also use the Name property of the frame tag    alert (frames["frame1"].document.title);

You can also use an ID in a frameset to get a reference to a child window

    var frame1 =document.getelementbyid ("frame1");//This just gets the label    var frame1win = frame1.contentwindow;// The Contentwindow of the Frame object contains a reference to the window    //can also get a reference to the document in the frame    var framedoc = frame1.contentdocument;    alert (framedoc);//But IE does not support contentdocument properties

BOM (Browser object model) browser objects models

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.