(Turn) BOM (Browser Object Model)

https://github.com/stone0090/javascript-lessons/tree/master/2.1-BOM
ECMAScript is the core of JavaScript, but if JavaScript is to be used on the web, the BOM (Browser Object Model) is undoubtedly the real thing core. The BOM provides many objects for accessing browser functionality independent of any web page content. Over the years, the lack of a de facto specification has led to a lot of problems with the BOM, as browser vendors extend it as they see fit. The W3C has incorporated major aspects of the BOM into the HTML5 specification in an effort to standardize the most basic parts of JavaScript in browsers.

The core object of the window object

BOM is window, which represents an instance of the browser. In the browser, the window object has dual roles, it is not only an interface for accessing the browser window through JavaScript, but also the Global object specified by ECMAScript. This means that any object, variable and function defined in the web page has window as its Global object, so it has access to isNaN(), isFinite(), parseInt(), parseFloat() and other methods.

Global Scope

Since the window object also plays the role of the Global object in ECMAScript, all variables and functions declared in the global scope will become properties and methods of the window object. Take a look at the example below.

var age = 29;
function sayAge(){
    console.log(this.age);
}

console.log(window.age); // 29
sayAge(); // 29
window.sayAge(); // 29
Aside from global variables that will become properties of the window object, defining global variables is the same as directly on the window object There is still a slight difference in defining properties: global variables cannot be deleted with the delete operator, while properties defined directly on the window object can. For example:

var age = 29;
window.color = "red";

// throws error in IE < 9, returns false in all other browsers
delete window.age;

// throws error in IE < 9 , which returns true in all other browsers
delete window.color; // return true

console.log(window.age); // 29
console.log(window.color); // undefined
window property added with var statement There is a property called Configurable, the value of this property is set to false by default, so properties defined in this way cannot be deleted by the delete operator. IE8 and earlier will throw an error as a warning when encountering a statement that uses delete to delete the window property, regardless of how the property was originally created. IE9 and later will not throw errors.

Also, keep one more thing in mind: trying to access an undeclared variable will throw an error, but by querying the window object, you can tell if a possibly undeclared variable exists. For example:

// this will throw an error because oldValue is undefined
var newValue = oldValue;

// this will not throw an error because this is a property query
// newValue's value is undefined
var newValue = window.oldValue;
window relation And frames

If the page contains frames, each frame has its own window object, which is stored in the frames collection. In the frames collection, the corresponding window object can be accessed by numerical index (0-based, left-to-right, top-to-bottom) or frame name. Each window object has a name property that contains the name of the frame. Here is a page with a frame:

<html>
    <head>
        <title>Frameset Example</title>
    </head>
    <frameset rows="160,*">
        <frame src="frame.htm" name="topFrame ">
        <frameset cols="50%,50%">
            <frame src="
            <frame src="yetanotherframe.htm" name="rightFrame">
        </frameset>
    </frameset>
</html>
For this example, pass window.frames[0] or window.frames["topFrame"] to reference the frame above. However, it is better to use top instead of window to refer to these frames (eg top.frames[0]), because the top object always points to the top (outermost) frame, which is the browser window. Use it to ensure proper access from one frame to another. Because for any code written in a frame, the window object points to a specific instance of that frame, not the top-level frame.

Another window object opposite top is parent. As the name implies, the parent object always points to the frame immediately above the current frame. In some cases, parent may be equal to top; but in the absence of a frame, parent must be equal to top (in which case they are both equal to window).

The last object associated with a frame is self, which always points to window; in fact, the self and window objects are used interchangeably. The purpose of introducing the self object is only to correspond to the top and parent objects, so it contains no other values ​​in particular.

All of these objects are properties of the window object, which can be accessed through window.parent, window.top, and so on. At the same time, this also means that different levels of window objects can be chained together, such as window.parent.parent.frames[0].

In the case of frameworks, there are multiple Global objects in the browser. Global variables defined in each frame automatically become properties of the window object in the frame. Since each window object contains constructors for primitive types, each framework has its own set of constructors that correspond one-to-one, but not equal. For example, top.Object is not equal to top.frames[0].Object. This issue affects the use of the instanceof operator on objects passed across frames.

Navigating and opening windows

Use the window.open() method to either navigate to a specific URL or to open a new browser window. This method accepts 4 parameters: the URL to load, the window target, an attribute string, and a boolean indicating whether the new page should replace the currently loaded page in the browser's history. Usually only the first parameter needs to be passed, and the last parameter is only used without opening a new window.

If a second parameter is passed to window.open() and that parameter is the name of an existing window or frame, the URL specified by the first parameter will be loaded in the window or frame with that name. See the example below.

// Equivalent to <a href="http://shijiajie.com" target="newWindow"></a>
window.open("http://shijiajie.com/", "newWindow");
popup window

if to window. The second parameter passed to open() is not an existing window or frame, then the method will create a new window or new tab based on the string passed in the third parameter position. If no third parameter is passed, then a new browser window (or a new tab) will be opened with all default settings (toolbar, address bar, status bar, etc.). The third parameter is ignored without opening a new window.

The third parameter is a comma-separated string of settings indicating which properties are displayed in the new window. The following table lists the setting options that can appear in this string.

Setting value description
fullscreen yes or no indicates whether the browser window is maximized. IE only
The height value represents the height of the new window. Can't be less than 100
left The value represents the left coordinate of the new window. Cannot be a negative value
location yes or no indicates whether to display the address bar in the browser window. Different browsers have different defaults. If set to no, the address bar may be hidden or disabled (depending on the browser)
menubar yes or no indicates whether to show the menu bar in the browser window. The default is no
resizable yes or no indicates whether the browser window can be resized by dragging its borders. The default value is no
scrollbars yes or no indicates whether to allow scrolling if the content does not fit in the viewport. The default value is no
status yes or no indicates whether to display the status bar in the browser window. The default value is no
toolbar yes or no indicates whether to display the toolbar in the browser window. The default value is no
top The value represents the top coordinate of the new window. Cannot be a negative value
The width value represents the width of the new window. Cannot be less than 100
This line of code will open a new resizable window with an initial size of 400 x 400 pixels and 10 pixels from the top and left of the screen.

window.open("http://shijiajie.com/","newWindow",
    "height=400,width=400,top=10,left=10,resizable=yes"); The
window.open() method returns a reference to the new window. The referenced object is roughly similar to other window objects, but we have more control over it. For example, some browsers may by default not allow us to resize or move the main browser window, but allow us to resize or move the window created via window.open(). With this returned object, the newly opened window can be manipulated like any other window, as shown below.

var win = window.open("http://shijiajie.com/","newWindow",
    "height=400,width=400,top=10,left=10,resizable=yes");

// resize
win .resizeTo(500,500);

// move the position
win.moveTo(100,100);

// close the window
win.close();
However, the close() method only works on popup windows opened via window.open(). The browser's main window cannot be closed without the user's permission.

The newly created window object has an opener property that holds the original window object that opened it. This property is only defined on the outermost window object (top) in a popup window, and points to the window or frame that called window.open(). For example:

var win = window.open("http://shijiajie.
    "height=400,width=400,top=10,left=10,resizable=yes");

console.log(win.opener === window); // true
although the popup window has a pointer to the one that opened it The original window, but there is no such pointer in the original window to the popup. Windows don't keep track of the popups they open, so we can only implement tracking manually when necessary.

Pop-up

Blockers There was a time when advertisers used pop-ups online to an unbridled level. They often dress up pop-ups as system dialogs to lure users into clicking on the ads. Because it looks like a system dialog, it is difficult for the average user to tell whether it is true or false. In order to solve this problem, most browsers have built-in pop-up window blocking programs, which block the pop-up windows that most users do not want to see.

Thus, when pop-ups are blocked, two possibilities should be considered. window.open() will most likely return null if it is a popup blocked by the browser's built-in blocker, and will usually throw an error if it is a popup blocked by a browser extension or other program . Therefore, to accurately detect whether a popup is blocked, the call to window.open() must be wrapped in a try-catch block along with the return value, as shown below.

var blocked = false;

try {
    var win = window.open("http://shijiajie.com", "_blank");
    if (win == null){
        blocked = true;
    }
} catch (ex){
    blocked = true;
}
if (blocked){ console.log
    ("The popup was blocked!");
}
Intermittent and timeout calls

A time value to schedule code to execute at a specific moment. The former executes the code after a specified time, while the latter executes the code every specified time.

The timeout call requires the use of the window object's setTimeout() method, which accepts two parameters: the code to execute and the time in milliseconds (ie, how many milliseconds to wait before executing the code). where the first argument can be a string containing JavaScript code (just like the string used in the eval() function) or a function. For example, the following two calls to setTimeout() show an alert box after one second.

// It is not recommended to pass the string
setTimeout("console.log('Hello world!') ", 1000);

// The recommended way to call
setTimeout(function() {
    console.log("Hello world!");
}, 1000);
while both calls are fine, passing a string as the first parameter is not recommended due to the possible performance penalty.

The second parameter is a number of milliseconds that indicates how long to wait, after which the specified code will not necessarily execute. JavaScript is an interpreter for a one-liner program, so only one piece of code can be executed at a certain time. To control the code to be executed, there is a queue of JavaScript tasks. The tasks are executed in the order in which they were added to the queue. The second parameter of setTimeout() tells JavaScript how long to wait to add the current task to the queue. If the queue is empty, the added code will be executed immediately; if the queue is not empty, then it will wait for the previous code to finish executing before executing.

After calling setTimeout(), the method returns a numeric ID indicating that the call has timed out. The timeout call ID is a unique identifier for the code that is scheduled to execute and can be used to cancel the timeout call. To cancel a scheduled timeout call that has not yet been executed, you can call the clearTimeout() method and pass it the corresponding timeout call ID as a parameter, as shown below.

// set timeout call
var timeoutId = setTimeout(function() {
    console. log("Hello world!");
}, 1000);

// Note: cancel it
clearTimeout(timeoutId);
as long as the specified time has not elapsed By calling clearTimeout() before, you can completely cancel the timeout call. The preceding code calls clearTimeout() immediately after setting the timeout call, and the result is as if nothing happened.

An intermittent call is similar to a timeout call, except that it executes code repeatedly at specified intervals until the intermittent call is canceled or the page is unloaded. The way to set intermittent calls is setInterval(), which accepts the same parameters as setTimeout(): the code (string or function) to execute and the number of milliseconds to wait before each execution. Let's look at an example.

// It is not recommended to pass the string
setInterval ("console.log('Hello world!') ", 10000);

// The recommended way to call
setInterval (function() {
    console.log("Hello world!");
}, 10000);
calling the setInterval() method also returns an intermittent call ID, which can be used to cancel the intermittent call at some point in the future. To cancel an interval call that has not yet been executed, use the clearInterval() method and pass in the corresponding interval call ID. Cancelling the intermittent call is far more important than canceling the timeout call, because without intervention, the intermittent call will execute until the page is unloaded. The following is a common example of using intermittent calls.

var num = 0;
var max = 10;
var intervalId = null;

function incrementNumber() {
    num++;
    // If the number of executions reaches the value set by max, cancel the subsequent calls that have not been executed
    if (num == max) {
        clearInterval(intervalId);
        console.log("Done");
    }
}

intervalId = setInterval(incrementNumber, 500);
In this example, the variable num is incremented every half second, and when it reaches the maximum value, the previous setting will be canceled scheduled intermittent calls. This pattern can also be implemented using timeout calls as shown below.

var num = 0;
var max = 10;

function incrementNumber() {
    num++;

    // If the number of executions does not reach the value set by max, set another timeout call
    if (num < max) {
        setTimeout(incrementNumber, 500);
    } else {
        console.log("Done");
    }
}

setTimeout(incrementNumber, 500);
It can be seen that when using a timeout call, it is not necessary to keep track of the timeout call ID, because after each execution of the code, if another timeout call is not set, the call will stop by itself. It is generally considered the best pattern to use timeout calls to simulate intermittent calls. In a development environment, true intermittent calls are rarely used because the latter may start before the previous one finishes. Using a timeout call, as in the previous example, avoids this entirely. So, it's better not to use intermittent calls.

System Dialogs

Browsers can call system dialogs to display messages to the user through the alert(), confirm(), and prompt() methods. System dialogs are not related to the web page displayed in the browser and do not contain HTML. Their appearance is determined by operating system and/or browser settings, not by CSS. In addition, dialogs opened by these methods are synchronous and modal. That is, the code stops executing when these dialogs are displayed, and resumes when the dialogs are closed.

The first dialog is generated by calling the alert() method. It displays a system dialog to the user with specified text and an OK ("OK") button. The "warning" dialog box generated by alert() is usually used to display messages to the user that they have no control over, such as error messages. The user can only close the dialog after reading the message.

The second type of dialog is generated by calling the confirm() method. This "confirmation" dialog is much like a "warning" dialog in terms of displaying a message to the user. But the main difference between the two is that the Confirm dialog box displays a Cancel button in addition to the OK button. Both buttons allow the user to decide whether or not to perform a given action.

To determine whether the user clicked OK or Cancel, check the boolean value returned by the confirm() method: true if OK was clicked, false if Cancel was clicked or the X button in the upper right corner was clicked. A typical usage of a confirmation dialog is as follows.

if (confirm("Are you sure?")) {
    alert("I'm so glad you're sure! ");
} else {
    alert("I'm sorry to hear you're not sure.");
}
The last type of dialog is generated by calling the prompt() method, which is a "prompt" box that prompts the user to enter some text. In addition to the OK and Cancel buttons, the prompt box displays a text input field for the user to enter. The prompt() method accepts two parameters: the text prompt to display to the user and the default value of the text input field (which can be an empty string).

If the user clicked the OK button, prompt() returns the value of the text input field; if the user clicked Cancel or otherwise closed the dialog without clicking OK, the method returns null. Below is an example.

var result = prompt("What is your name? ", "");
if (result !== null) {
    alert("Welcome, " + result);
}
To sum up, these system dialogs are great for showing the user Display a message and ask the user to make a decision. They are a convenient way to enhance web applications because there is no HTML, CSS, or JavaScript involved.

location object

The location object provides information about the document loaded in the current window and also provides some navigation capabilities. In fact, the location object is very special because it is a property of both the window object and the document object; in other words, window.location and document.location refer to the same object. The usefulness of the location object is not only that it holds information about the current document, but also that it parses URLs into separate fragments that developers can access through different properties. The following table lists all the properties of the location object.

Attribute name example description
hash "#contents" returns the hash in the URL (# sign followed by zero or more characters), or an empty string if the URL does not contain a hash
host "shijiajie.com:80" returns the server name and port number (if any)
hostname "shijiajie.com" returns the server name without the port number
href "http:/shijiajie.com" returns the full URL of the currently loaded page. The toString() method of the location object also returns this value
pathname "/WileyCDA/" returns the directory and/or file name
in the URL port "8080" returns the port number specified in the URL. If the URL does not contain a port number, this property returns the empty string
protocol "http:" Returns the protocol used by the page. Usually http: or https:
search "?q=javascript" Returns the query string of the URL.
This string starts with a question mark Query String Parameters

Although most of the information about the location object can be accessed through the above properties, it is not convenient to access the properties of the query string contained in the URL. Although location.search returns everything from the question mark to the end of the URL, there is no way to access each query string parameter in it individually. To do this, create a function like this that parses the query string and returns an object containing all the parameters:

/*
* This function parses the name=value parameter pair in the query string from the URL
* it will The name=value pair is stored in a property of an object, and that object is returned
* this way to use it
*
* var args = urlArgs(); // parse arguments from URL
* var q = args.q || ""; / / use the parameter if it is defined; otherwise use a default value
* var n = args.n ? parseInt(args.n) : 10;
*/
function urlArgs() {
    var args = {}; // define an empty Object
    var query = location.search.substring(1); // Find the query string and remove '?'
    var pairs = query.split("&"); // Separate the query string according to the "&" symbol open
    for (var i = 0; i < pairs.length; i++) { // for each fragment
        var pos = pairs[i].indexOf('='); // look for "name=value"
        if (pos == -1) continue; // skip if not found
        var name = pairs[i].substring(0, pos); // extract name
        var value = pairs[i].substring(pos + 1); / / extract value
        value = decodeURIComponent(value); // decode value
        args[name] = value; // store as attribute
    }
    return args; // return parsed parameter
}
location manipulation There are many ways to

use the location object Change the location of the browser. The first, and most common way, is to use the assign() method and pass it a URL, as shown below.

location.assign("http://shijiajie.com");
This way, the new URL can be opened immediately and a record made in the browser's history. If location.href or window.location is set to a URL value, the assign() method is also called with that value. For example, the following two lines of code have exactly the same effect as explicitly calling the assign() method.

window.location = "http://shijiajie.com";
location.href = "http://shijiajie.com";
Among these methods of changing the browser's location, the most commonly used is to set the location.href property.

In addition, modifying other properties of the location object can also change the currently loaded page. The following example shows changing the URL by setting the hash, search, hostname, pathname and port properties to new values.

// Assume the initial URL is http://shijiajie.com/about/
location.href = "http://shijiajie.com/about/"

// Modify the URL to "http://shijiajie.com/about/# ds-thread"
location.hash = "#ds-thread";

// Change the URL to "http://shijiajie.com/about/?args=123"
location.search = "?args=123";

// Change the URL to "https:
location.hostname = "segmentfault.com";

// Change the URL to "http://segmentfault.com/u/stone0090/"
location.pathname = "u/stone0090";

// Change the URL to "https:/ /segmentfault.com:8080/"
location.port = 8080;
When the URL is modified in any of the above ways, a new record is generated in the browser's history, so the user will navigate to previous page. To disable this behavior, use the replace() method. This method accepts only one parameter, the URL to navigate to; the result will cause the browser location to change, but will not generate a new record in the history. After calling the replace() method, the user cannot go back to the previous page, see the following example:

<!DOCTYPE html>
<html>
<head>
    <title>You won't be able to get back here</title>
</head>
    <body>
    <p>Enjoy this page for a second, because you won't be coming back here.</p>
    <script type="

            location.replace("http://shijiajie.com/");
        }, 1000);
    </script>
</body>
</html>
If this page is loaded into the browser, the browser will Zhong Hou redirects to shijiajie.com. The Back button will then be disabled and there is no way to go back to the example page without re-entering the full URL.

The last method related to position is reload(), which reloads the currently displayed page. If you call reload() with no arguments, the page will reload in the most efficient way possible. That is, if the page has not changed since the last request, the page is reloaded from the browser cache. If you want to force a reload from the server, you need to pass the parameter true to the method like below.

location.reload(); // reload (possibly from cache)
location.reload(true); // reload (reload from server)
code after the reload() call may or may not be executed , depending on factors such as network latency or system resources. For this, it is best to put reload() on the last line of code.

history object

The history object saves the user's surfing history from the moment the window is opened. Because history is a property of the window object, each browser window, each tab, and even each frame has its own history object associated with a specific window object. For security reasons, developers have no way of knowing which URLs users have viewed. However, it is also possible to go back and forward without knowing the actual URL, using the list of pages the user has visited.

Use the go() method to jump anywhere in the user's history, either backward or forward. This method accepts one parameter, an integer value representing the number of pages to jump backwards or forwards. Negative numbers jump backward (similar to clicking the browser's "back" button), and positive numbers jump forward (similar to clicking the browser's "forward" button). Take a look at the example below.

// go back one page
history.go(-1);

// go forward one page
history.go(1);

// go forward two pages
history.go(2);
you can also pass a string parameter to the go() method, At this point the browser will jump to the first position in the history that contains the string - either back or forward, depending on which position is closest. If the string is not included in the history, this method does nothing, for example:

// Jump to the nearest shijiajie.com page
history.go("shijiajie.com");
Also, two shorthands can be used The methods back() and forward() replace go(). As the name suggests, these two methods mimic the browser's "back" and "forward" buttons.

// go back one page
history.back();

// Forward one page
history.forward();
In addition to the above methods, the history object also has a length property, which saves the number of history records. This number includes all historical records, i.e. all backward and forward records. For the first page loaded into a window, tab, or frame, history.length is equal to 0. By testing the value of this property like the following, you can determine whether the user opened your page in the first place.

if (history.length == 0){
    //this should be the first page after the user opens the window
}
Although history is not commonly used, it is useful to create custom "back" and "forward" buttons, and to detect the current page It must still be used when it is not the first page in the user's history.

Summary

The BOM (Browser Object Model) relies on the window object, which represents the browser window and the visible area of ​​the page. At the same time, the window object is also the Global object in ECMAScript, so all global variables and functions are its properties, and all native constructors and other functions also exist under its namespace. This chapter discusses the following components of the BOM.

When using frameworks, each framework has its own window object and a copy of all native constructors and other functions. Each frame is kept in the frames collection, which can be accessed by location or by name.
There are some window pointers that can be used to refer to other frames, including the parent frame.
The top object always points to the outermost frame, which is the entire browser window.
The parent object represents the frame containing the current frame, while the self object refers back to window.
Use the location object to programmatically access the browser's navigation system. By setting the corresponding properties, you can modify the URL of the browser segment by segment or as a whole.
Calling the replace() method navigates to a new URL that replaces the page currently displayed in the browser's history.
The navigator object provides information about the browser. Exactly what information is provided depends largely on the user's browser; however, there are some common properties (such as userAgent) that are present in all browsers.
There are also two objects in the BOM: screen and history, but their functionality is limited. The screen object holds information about the client's display, which is generally only used for site analysis. The history object opens a small gap for accessing the browser's history, allowing developers to determine the amount of history, and to navigate backwards or forwards to any page in the history.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327060131&siteId=291194637