Script browser window

Source: Internet
Author: User
1. Timer

An important function of any programming environment is to plan code execution at some point in the future. The core JavaScript language does not provide such a function, but client JavaScript does provide this function in the form of global functions setTimeout (), cleartimeout (), setinterval (), and clearinterval.

The setTimeout () method of the window object is used to schedule a function to run after a specified number of milliseconds. SetTimeout () returns an uncertain value, which can be passed to cleartimeout () to cancel the execution of the planned function.

Setinterval () is the same as setTimeout (), but the specified function is repeatedly called at a specified interval of milliseconds. Like setTimeout (), setinterval () also returns an uncertain value, which can be passed to any future call of clearinterval () to cancel the planned function.

2. browser location and history

These two objects provide access to the URL of the currently displayed document, and allow loading of new documents or turning the browser back (or forward) to a previously viewed document.

2.1 parse URL

The location attribute of the window references the location object, which represents the URL of the currently displayed document in the window (or frame. The href attribute of the location object is a string that contains the complete text of the URL. The location object tostring () method returns the value of the href attribute. Therefore, you can use location instead of location. href.

2.2 load new documents

Although the location attribute of a window references a location object, you can assign a string to this property. In this case, the browser interprets the string as a URL and tries to use this URL to load and display the document.

The location object can be loaded and displayed in a browser in two ways.

Method reload () will load the current page from the Web server again. The method Replace () loads and displays the specified URL. When this method is called for a given URL, the location attribute assigned to the window by a URL is different. When Replace () is called, the specified URL replaces the current URL in the browser history list, instead of creating a new entry in the History list. Therefore, if you use Replace () to overwrite the current document with a new document, the back button will not allow the user to return the original document, this can be done by assigning a URL to the location attribute of the window to load new documents.

Note: Do not confuse the location attribute of the window object with the location attribute of the Document Object. The former references a location object, while the latter is a read-only string and does not have any features of the location object. Document. Location is synonymous with document. url, which is a candidate name for this attribute. In most cases, document. Location and location. href are the same. At that time, when server redirection exists, document. location contains the loaded URL, while location. href contains the URL of the original request document.

2.3. History Object

The history attribute of the window object references the history object of the window. The history object was originally used to construct the browsing history of the window into an array of recently accessed URLs.

Although the array element of the history object cannot be accessed, it supports three methods. Methods back () and forward () can be moved before and after the browsing history of a window (or frame), replacing the currently displayed document with the previously viewed document, this is the same as clicking the back and forward buttons in the browser. The third method, go (), has an integer parameter. You can skip multiple pages in the history list, either forward (positive) or backward (negative.

3. Obtain window, screen, and browser Information

Sometimes the script needs to obtain information related to the window, desktop, or browser in which it runs.

3.1. Window SET SIZE

The following detailed example defines a geometry object with a portable Method for querying the size, position of the moving bar, and position of the screen.

/** * Geometry.js: portable functions for querying window and document geometry * * This module defines functions for querying window and document geometry. *  * getWindowX/Y(): return the position of the window on the screen * getViewportWidth/Height(): return the size of the browser viewport area * getDocumentWidth/Height(): return the size of the document. * getHorizontalScroll(): return the position of the horizontal scrollbar * getVerticalScroll(): return the position of the vertical scrollbar * * Note that there is no portable way to query the overall size of the  * browser window, so there are no getWindowWidth/Height() functions. *  * IMPORTANT: This module must be included in the <body> of a document *            instead of the 
 

3.2. Screen Object

The screen attribute of the window object references the Screen Object. This screen object provides information about the user's display size and available color quantity. The property width and height specify the display size in pixels. The availwidth and availheight attributes specify the actual available display size, excluding the space occupied by features such as the desktop taskbar.

3.3 navigator object

The navigator attribute of the window object references the navigator object that contains the overall information of the web browser, such as the version and the list of data formats that it can display.

The navigator object has five attributes used to provide version information for a running Browser:

Appname: the simple name of the browser.

Appversion: the version number and/or other version information of the browser.

Useragent: string sent by the browser in its User-Agent HTTP header. This attribute usually contains all information in appname and appversion, and may also contain other details.

Appcodename: the code number of the browser.

Platform: the hardware platform that runs the browser.

4. Open and operate windows
4.1 open a window

The window. open () method can open a new browser window. The returned window object represents the new window. The first parameter of open () is the URL of the document to be displayed in the new window, the second parameter is the name of the newly opened window, and the third parameter is the feature list, the fourth parameter is only useful when the second parameter is named as an existing window.

4.2 close the window

Just as the method open () opens a new window, the method close () closes a window.

4.3. Window Geometric Size

You can use moveTo () to move the upper left corner of the window to the specified coordinates. Similarly, moveBy () can move the window up, down, or left, or right to a specified number of pixels. Methods resizeTo () and resizeBy () can adjust the window size according to the relative quantity and absolute quantity.

4.4. keyboard focus and visibility

The method focus () will request the system to assign the keyboard focus to the window, and blur () will discard the keyboard focus.

4.5. Scroll

Window objects also have methods for scrolling documents in Windows or frames. Scrollby () will scroll the specified number of pixels to the left, right, or up or down of the document displayed in the window. Scrollto () will scroll the document to an absolute position.

In modern browsers, the HTML elements of a document have the offsetleft and offsettop attributes to specify the X and Y coordinates of the element. Once the element position has been determined, you can use scrollto () to scroll a window so that any specified element is located in the upper left corner of the window.

Another method of scrolling is to call the focus () method of document elements (such as form fields or buttons), which can receive the keyboard focus. As part of the process of passing the focus to the element, scroll the document to make the element visible.

4.6 window method example

<script>var bounce = {    x:0, y:0, w:200, h:200,   // Window position and size    dx:5, dy:5,               // Window velocity    interval: 100,            // Milliseconds between updates    win: null,                // The window we will create    timer: null,              // Return value of setInterval()    // Start the animation    start: function() {         // Start with the window in the center of the screen         bounce.x = (screen.width - bounce.w)/2;         bounce.y = (screen.height - bounce.h)/2;         // Create the window that we're going to move around         // The javascript: URL is simply a way to display a short document         // The final argument specifies the window size         bounce.win = window.open('javascript:"
 

5. Simple dialog box

Use alert (), confirm (), and prompt ().

6. Scripted Status Bar

An elegant status bar Animation

<script>var WastedTime = {    start: new Date(),   // Remember the time we started    displayElapsedTime: function() {        var now = new Date();  // What time is it now        // compute elapsed minutes        var elapsed = Math.round((now - WastedTime.start)/60000);         // And try to display this in the status bar        window.defaultStatus = "You have wasted " + elapsed + " minutes.";    }}// Update the status line every minutesetInterval(WastedTime.displayElapsedTime, 60000);</script>

7. handle errors

The onerror attribute of the window object is special. If a function is assigned to this attribute, the function will be called as long as a javascript error occurs in the window, that is, it becomes the window error handling handle.

8. Multi-Window and multi-Frame
8.1 relationship between frames
8.2. Window and frame name
8.3. Javascript in the interaction window

9. Example: A navigation bar in the frame

<!--  This file implements a navigation bar, designed to go in a frame.  Include it in a frameset like the following:    <frameset rows="*,75">      <frame src="about:blank" name="main">      <frame src="navigation.html">    </frameset>  The code in this file will control the contents of the frame named "main"--><script>// The function is invoked by the Back button in our navigation barfunction back() {    // First, clear the URL entry field in our form    document.navbar.url.value = "";    // Then use the History object of the main frame to go back    // Unless the same-origin policy thwarts us    try { parent.main.history.back(); }    catch(e) { alert("Same-origin policy blocks History.back(): " + e.message); }    // Display the URL of the document we just went back to, if we can.    // We have to defer this call to updateURL() to allow it to work.    setTimeout(updateURL, 1000);}// This function is invoked by the Forward button in the navigation bar.function forward() {    document.navbar.url.value = "";    try { parent.main.history.forward(); }    catch(e) { alert("Same-origin policy blocks History.forward(): "+e.message);}    setTimeout(updateURL, 1000);}// This private function is used by back() and forward() to update the URL// text field in the form.  Usually the same-origin policy prevents us from// querying the location property of the main frame, however.function updateURL() {    try { document.navbar.url.value = parent.main.location.href; }    catch(e) {        document.navbar.url.value = "<Same-origin policy prevents URL access>";    }}// Utility function: if the url does not begin with "http://", add it.function fixup(url) {    if (url.substring(0,7) != "http://") url = "http://" + url;    return url;}// This function is invoked by the Go button in the navigation bar and also// when the user submits the formfunction go() {    // And load the specified URL into the main frame.    parent.main.location = fixup(document.navbar.url.value);}// Open a new window and display the URL specified by the user in itfunction displayInNewWindow() {    // We're opening a regular, unnamed, full-featured window, so we just    // need to specify the URL argument.  Once this window is opened, our    // navigation bar will not have any control over it.    window.open(fixup(document.navbar.url.value));}</script><!-- Here's the form, with event handlers that invoke the functions above --><form name="navbar" onsubmit="go(); return false;">  <input type="button" value="Back" onclick="back();">  <input type="button" value="Forward" onclick="forward();">  URL: <input type="text" name="url" size="50">  <input type="button" value="Go" onclick="go();">  <input type="button" value="Open New Window" onclick="displayInNewWindow();"></form>

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.