window object

Overview

In the browser, the window object (note that w is lowercase) refers to the current browser window. It is also the top-level object of the current page, that is, the highest-level object, and all other objects are its subordinates. If a variable is not declared, it defaults to the attribute of the top-level object.

a = 1;
window.a; // 1

In the above code, a is a variable that is assigned directly without declaration, and it automatically becomes a property of the top-level object.

Window has its own entity meaning, but it is not suitable for being the top-level object at the highest level. This is a design error of the language. At the earliest, when designing this language, the original idea was that the fewer built-in objects in the language, the better, which would improve the performance of the browser. Therefore, the language designer Brendan Eich regards the window object as the top-level object, and all variables assigned without being declared automatically become the properties of the window object. This design makes it impossible to detect undeclared variables at the compilation stage, but today there is no way to correct them.

Properties of the window object

window.name

The window.name property is a string that represents the name of the current browser window. The window does not necessarily need a name, this attribute is mainly used in conjunction with the target attribute of hyperlinks and forms.

window.name = "Hello World!";
console.log(window.name);
// "Hello World!"

This attribute can only save character strings. If the written value is not a character string, it will be automatically converted into a character string. The storage capacity of this value varies from browser to browser, but in general, it can be as high as several MB.

As long as the browser window is not closed, this property will not disappear. For example, when visiting a.com, the script of the page is set to window.name, and then b.com is loaded in the same window, and the script of the new page can be read to the previous page The set window.name. This is also the case for page refresh. Once the browser window is closed, the value saved by this property will disappear, because the window no longer exists at this time.

window.closed, window.opener

The window.closed property returns a boolean value indicating whether the window is closed.

window.closed; // false

The above code checks whether the current window is closed. This check is of little significance, because as long as the code can be run, the current window is definitely not closed. This attribute is generally used to check whether the new window opened by the script is closed.

var popup = window.open();

if (popup !== null && !popup.closed) {
  // The window is still open
}

The window.opener property represents the parent window that opened the current window. If the current window does not have a parent window (that is, directly enter the address bar to open it), null is returned.

window.open().opener === window; // true

The above expression will open a new window and return true.

If there is no need to communicate between the two windows, it is recommended to explicitly set the opener property of the child window to null, which can reduce some security risks.

var newWin = window.open("example.html", "newWindow", "height=400,width=400");
newWin.opener = null;

In the above code, the opener property of the child window is set to null, and there is no way to communicate between the two windows.

Through the opener property, the global properties and methods of the parent window can be obtained, but only when the two windows are of the same origin (see the chapter "Restrictions on the Same Origin"), and one of the windows is opened by the other. Adding the rel="noopener" attribute to the <a> element can prevent newly opened windows from acquiring the parent window and reduce the risk of malicious websites modifying the parent window URL.

<a href="https://an.evil.site" target="_blank" rel="noopener">
  Malicious website
</a>

window.self, window.window

Both window.self and window.window properties point to the window itself. These two attributes are read-only.

window.self === window; // true
window.window === window; // true

window.frames, window.length

The window.frames property returns an array-like object. The members are all frame windows in the page, including the frame element and the iframe element. window.frames[0] means the first frame window in the page.

If the iframe element is set with the id or name attribute, then the attribute value can be used to refer to the iframe window. For example, <iframe name="myIFrame"> can be referenced with frames['myIFrame'] or frames.myIFrame.

The frames property is actually an alias for the window object.

frames === window; // true

Therefore, frames[0] can also be represented by window[0]. However, from a semantic point of view, frames is clearer, and considering that window is still a global object, it is recommended to always use frames[0] when expressing multiple windows. For more introduction, please see the "Multi-Window Operation" section below.

The window.length property returns the total number of frames contained in the current web page. If the current webpage does not contain frame and iframe elements, then window.length returns 0.

window.frames.length === window.length; // true

The above code indicates that window.frames.length and window.length should be equal.

window.frameElement

The window.frameElement property is mainly used when the current window is embedded in another webpage (embedded <object>, <iframe> or <embed> element), and returns the element node where the current window is located. If the current window is the top-level window, or the embedded web page is not of the same origin, this attribute returns null.

// HTML code is as follows
// <iframe src="about.html"></iframe>

// The following script is in about.html
var frameEl = window.frameElement;
if (frameEl) {
  frameEl.src = "other.html";
}

In the above code, the frameEl variable is the <iframe> element.

window.top, window.parent

The window.top property points to the topmost window, which is mainly used to obtain the topmost window in the frame.

The window.parent property points to the parent window. If the current window has no parent window, window.parent points to itself.

if (window.parent !== window.top) {
  // Indicates that the current window is embedded in more than one layer
}

For web pages that do not contain frames, these two properties are equivalent to the window object.

window.status

The window.status property is used to read and write the text of the browser status bar. However, many browsers do not allow the status bar text to be rewritten, so this method may not be effective.

window.devicePixelRatio

The window.devicePixelRatio property returns a value that represents the ratio between the size of a CSS pixel and the size of a physical pixel. In other words, it indicates how many physical pixels a CSS pixel consists of. It can be used to determine the user's display environment. If this ratio is large, it means that the user is using a high-definition screen, so larger-pixel pictures can be displayed.

Location size attribute

The following properties return the position and size information of the window object.

(1) window.screenX, window.screenY

The window.screenX and window.screenY properties return the horizontal and vertical distance (in pixels) of the upper left corner of the browser window relative to the upper left corner of the current screen. These two attributes are read-only.

(2) window.innerHeight, window.innerWidth

The window.innerHeight and window.innerWidth properties return the height and width of the visible part of the web page in the current window, that is, the size (in pixels) of the "viewport". These two attributes are read-only.

When the user enlarges the webpage (for example, the webpage is enlarged from 100% to 200%), these two attributes will become smaller. Because the pixel size of the web page remains unchanged (for example, the width is still 960 pixels), but the screen space occupied by each pixel becomes larger, so the visible part (viewport) becomes smaller.

Note that these two attribute values ​​include the height and width of the scroll bar.

(3) window.outerHeight, window.outerWidth

The window.outerHeight and window.outerWidth properties return the height and width of the browser window, including the browser menu and border (in pixels). These two attributes are read-only.

(4) window.scrollX, window.scrollY

The window.scrollX property returns the horizontal scroll distance of the page, and the window.scrollY property returns the vertical scroll distance of the page, both in pixels. These two attributes are read-only.

Note that the return value of these two attributes is not an integer, but a double-precision floating-point number. If the page is not scrolling, their value is 0.

For example, if the user pulls down the vertical scroll bar by 75 pixels, then window.scrollY is about 75 pixels. The user pulls the horizontal scroll bar to the right by 200 pixels, and window.scrollX is about 200.

if (window.scrollY < 75) {
  window.scroll(0, 75);
}

In the above code, if the page scrolls down by less than 75 pixels, then the page scrolls down by 75 pixels.

(5) window.pageXOffset, window.pageYOffset

The window.pageXOffset property and the window.pageYOffset property are aliases of window.scrollX and window.scrollY.

Component properties

The component property returns the component object of the browser. There are several such attributes.

-window.locationbar: address bar object -window.menubar: Menu bar object -window.scrollbars: the scrollbar object of the window -window.toolbar: Toolbar object -window.statusbar: status bar object -window.personalbar: personal toolbar object installed by the user

The visible property of these objects is a boolean value that indicates whether these components are visible. These attributes are read-only.

window.locationbar.visible;
window.menubar.visible;
window.scrollbars.visible;
window.toolbar.visible;
window.statusbar.visible;
window.personalbar.visible;

Global Object Properties

Global object properties point to some global objects native to the browser.

-window.document: points to the document object, see the chapter "document object" for details. Note that this attribute has homology restrictions. Only scripts from the same source can read this attribute. -window.location: points to the Location object, used to obtain the URL information of the current window. It is equivalent to the document.location property, see the chapter "Location Object" for details. -window.navigator: points to the Navigator object, used to obtain environmental information, see the chapter "Navigator Object" for details. -window.history: points to the History object, representing the browsing history of the browser, see the chapter "History Object" for details. -window.localStorage: points to the localStorage data stored locally, see the chapter "Storage Interface" for details. -window.sessionStorage: points to the sessionStorage data stored locally, see the chapter "Storage Interface" for details. -window.console: points to the console object, used to operate the console, see the chapter "console object" for details. -window.screen: Point to the Screen object, representing screen information, see the chapter "Screen Object" for details.

window.isSecureContext

The window.isSecureContext property returns a boolean value indicating whether the current window is in an encrypted environment. If it is the HTTPS protocol, it is true, otherwise it is false.

Methods of the window object

window.alert(), window.prompt(), window.confirm()

window.alert(), window.prompt(), and window.confirm() are all global methods for the browser to interact with the user. They will pop up different dialogs, asking the user to respond. Note that the dialog boxes popped up by these three methods are all uniformly specified by the browser and cannot be customized.

(1) window.alert()

The dialog box popped up by the window.alert() method has only an "OK" button, which is often used to notify the user of certain information.

window.alert("Hello World");

The dialog box will disappear only if the user clicks the "OK" button. During the pop-up of the dialog box, the browser window is frozen. If you don't click the "OK" button, the user can't do anything.

The parameters of the window.alert() method can only be strings, and CSS styles cannot be used, but line breaks can be specified with \n.

alert("This prompt\n is divided into two lines");

(2) window.prompt()

In the dialog box popped up by the window.prompt() method, below the prompt text, there is an input box that requires the user to input information, and there are two buttons "OK" and "Cancel". It is often used to obtain data entered by the user.

var result = prompt("Your age?", 25);

The above code will pop up a dialog box with the text prompt "Your age?", asking the user to enter their age in the dialog box (25 is displayed by default). The value entered by the user will be stored in the variable result as the return value.

The return value of window.prompt() has two cases, it may be a string (it may be an empty string), or it may be null. Specifically, it is divided into three situations.

  1. The user enters information and clicks "OK", the information entered by the user is the return value.
  2. The user directly clicks "OK" without inputting information, and the default value of the input box is the return value.
  3. The user clicks "Cancel" (or presses the ESC button), the return value is null.

The second parameter of the window.prompt() method is optional, but it is best to always provide the second parameter as the default value of the input box.

(3) window.confirm()

In the dialog box popped up by the window.confirm() method, in addition to the prompt information, there are only two buttons, "OK" and "Cancel", which are often used to ask the user for consent.

var result = confirm("How are you recently?");

The above code pops up a dialog box with only one line of text "How are you?", the user chooses to click "OK" or "Cancel".

The confirm method returns a boolean value. If the user clicks "OK", it returns true; if the user clicks "Cancel", it returns false.

var okay = confirm("Please confirm this message.");
if (okay) {
  // User presses "OK"
} else {
  // User presses "Cancel"
}

One use of confirm is that when the user leaves the current page, a dialog box will pop up, asking if the user really wants to leave.

window.onunload = function () {
  return window.confirm(
    "Are you sure you want to leave the face-to-face page?"
  );
};

These three methods all have a blocking effect. Once the dialog box pops up, the entire page is suspended for execution, waiting for the user to respond.

window.open(), window.close(), window.stop()

(1) window.open()

The window.open method is used to create another browser window, similar to the new window option in the browser menu. It will return a reference to the new window, if it cannot create a new window, it will return null.

var popup = window.open("somefile.html");

The above code will make the browser pop up a new window, the URL is somefile.html under the current domain name.

The open method can accept a total of three parameters.

window.open(url, windowName, [windowFeatures]);

-url: A string representing the URL of the new window. If omitted, the default URL is about:blank. -windowName: A string representing the name of the new window. If the window with this name already exists, the window will be occupied and no new window will be created. If omitted, _blank is used by default, which means to create a new window without a name. There are also several preset values, _self means the current window, _top means the top-level window, and _parent means the upper-level window. -windowFeatures: string, the content is a comma-separated key-value pair (see below for details), indicating the parameters of the new window, such as whether there is a prompt bar, toolbar, etc. If omitted, a new window with a complete UI will be opened by default. If the newly created window is an existing window, this parameter will not work, and the browser will use the parameters of the previous window.

Below is an example.

var popup = window.open(
  "somepage.html",
  "DefinitionsWindows",
  "height=200,width=200,location=no,status=yes,resizable=yes,scrollbars=yes"
);

The above code indicates that the height and width of the opened new window are both 200 pixels, there is no address bar, but there is a status bar and scroll bar, allowing users to adjust the size.

The third parameter can be set as the following attributes.

-left: the distance (in pixels) of the new window from the leftmost side of the screen. Note that the new window must be visible and cannot be set outside the screen. -top: The distance (in pixels) of the new window from the top of the screen. -height: The height (in pixels) of the content area of ​​the new window, which must not be less than 100. -width: The width (in pixels) of the content area of ​​the new window, which must not be less than 100. -outerHeight: the height (in pixels) of the entire browser window, which must not be less than 100. -outerWidth: the width (in pixels) of the entire browser window, which must not be less than 100. -menubar: Whether to display the menu bar. -toolbar: Whether to display the toolbar. -location: Whether to display the address bar. -personalbar: Whether to display the toolbar installed by the user. -status: Whether to display the status bar. -dependent: Whether to rely on the parent window. If it depends, then the parent window is minimized and the window is also minimized; when the parent window is closed, the window is also closed. -minimizable: Whether there is a minimize button, provided that dialog=yes. -noopener: The new window will be disconnected from the parent window, that is, the window.opener property of the new window returns null, and the window.open() method of the parent window also returns null. -resizable: Whether the new window can be resized. -scrollbars: Whether to allow scroll bars to appear in the new window. -dialog: Whether there are controls for maximizing, minimizing, and restoring the original size in the title bar of the new window. -titlebar: Whether to display the title bar in the new window. -alwaysRaised: Whether to display at the top of all windows. -alwaysLowered: Whether to display at the bottom of the parent window. -close: Whether to display the close button in the new window.

For those attributes that can be turned on and off, setting it to yes or 1 or not setting any value means turning it on. For example, status=yes, status=1, and status will all get the same result. If you want to turn it off, you don't need to write no, but just omit this attribute. In other words, if some attributes are set in the third parameter, other yes/no attributes that are not set will be set to no, except for titlebar and close button (their values ​​default to yes).

For the above attributes, the attribute name and the attribute value are connected by an equal sign, and the attribute and the attribute are separated by a comma.

"height=200,width=200,location=no,status=yes,resizable=yes,scrollbars=yes";

In addition, although the second parameter of the open() method can specify an existing window, it does not mean that it can control other windows arbitrarily. In order to prevent being controlled by irrelevant windows, the browser only allows the open method to point to the window when the two windows are of the same origin, or the target window is opened by the current webpage.

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

var windowB = window.open("windowB.html", "WindowB");
windowB.window.name; // "WindowB"

Note that if the new window and the parent window are not of the same origin (that is, they are not in the same domain), they cannot obtain the internal properties of each other's window objects.

Here is another example.

var w = window.open();
console.log("A new window has been opened");
w.location = "http://example.com";

The above code first opens a new window, then a dialog box pops up in the window, and then directs the URL to example.com.

Because the open method is easily abused, many browsers do not allow scripts to automatically create new windows by default. Only when the user clicks a link or button, the script reacts and a new window pops up. Therefore, it is necessary to check whether the new window is opened successfully.

var popup = window.open();
if (popup === null) {
  // failed to create a new window
}

(2) window.close()

The window.close method is used to close the current window, generally only used to close the window created by the window.open method.

popup.close();

This method is only valid for the top-level window, and it is invalid for windows in the iframe frame.

(3) window.stop()

The window.stop() method is completely equivalent to clicking the stop button of the browser, which will stop loading objects such as images and videos that are or waiting to be loaded.

window.stop();

window.moveTo(), window.moveBy()

The window.moveTo() method is used to move the browser window to the specified location. It accepts two parameters, the horizontal distance and the vertical distance from the upper left corner of the window to the upper left corner of the screen, in pixels.

window.moveTo(100, 200);

The above code moves the window to the position of the screen (100, 200).

The window.moveBy() method moves the window to a relative position. It accepts two parameters, the horizontal distance of the upper left corner of the window to move to the right and the vertical distance of downward movement, in pixels.

window.moveBy(25, 50);

The above code moves the window 25 pixels to the right and 50 pixels down.

In order to prevent someone from abusing these two methods and moving the user's window at will, there is only one situation at present. The browser allows the window to be moved with a script: the window is created with the window.open() method, and there is only one in the window. Tab page. In other cases, using the above two methods is invalid.

window.resizeTo(), window.resizeBy()

The window.resizeTo() method is used to resize the window to the specified size.

It accepts two parameters. The first is the zoomed window width (the outerWidth property, including scroll bars, title bars, etc.), and the second is the zoomed window height (the outerHeight property).

window.resizeTo(window.screen.availWidth / 2, window.screen.availHeight / 2);

The above code zooms the current window to half the width and height of the available area of ​​the screen.

The window.resizeBy() method is used to resize the window. The difference between it and window.resizeTo() is that it scales by a relative amount, and window.resizeTo() needs to give the absolute size after scaling.

It accepts two parameters, the first is the amount of horizontal scaling, and the second is the amount of vertical scaling, both in pixels.

window.resizeBy(-200, -200);

The above code reduces the width and height of the current window by 200 pixels.

window.scrollTo(), window.scroll(), window.scrollBy()

The window.scrollTo method is used to scroll the document to the specified position. It accepts two parameters, which represent the page coordinates in the upper left corner of the window after scrolling.

window.scrollTo(x - coord, y - coord);

It can also accept a configuration object as a parameter.

window.scrollTo(options);

The configuration object options has three attributes.

-top: The vertical coordinate of the upper left corner of the page after scrolling, that is, the y coordinate. -left: The horizontal coordinate of the upper left corner of the page after scrolling, that is, the x coordinate. -behavior: string, indicating the way of scrolling, there are three possible values ​​(smooth, instant, auto), the default value is auto.

window.scrollTo({
  top: 1000,
  behavior: "smooth",
});

The window.scroll() method is an alias of the window.scrollTo() method.

The window.scrollBy() method is used to scroll the webpage by a specified distance (in pixels). It accepts two parameters: pixels to scroll horizontally to the right, and pixels to scroll vertically down.

window.scrollBy(0, window.innerHeight);

The above code is used to scroll the web page down one screen.

If you do not want to scroll the entire document, but to scroll an element, you can use the following three properties and methods.

-Element.scrollTop -Element.scrollLeft -Element.scrollIntoView()

window.print()

The window.print method will jump out of the print dialog box, which has the same effect as the user clicking the "print" command in the menu.

Common print button codes are as follows.

document.getElementById("printLink").onclick = function () {
  window.print();
};

Non-desktop devices (such as mobile phones) may not have the printing function, you can judge this way at this time.

if (typeof window.print === "function") {
  // Support printing function
}

window.focus(), window.blur()

The window.focus() method will activate the window, make it focus, and appear in front of other windows.

var popup = window.open("popup.html", "Popup Window");

if (popup !== null && !popup.closed) {
  popup.focus();
}

The above code first checks whether the popup window still exists, and activates the window after confirmation.

The window.blur() method removes the focus from the window.

When the current window gains focus, the focus event will be triggered; when the current window loses focus, the blur event will be triggered.

window.getSelection()

The window.getSelection method returns a Selection object, which represents the text currently selected by the user.

var selObj = window.getSelection();

Use the toString method of the Selection object to get the selected text.

var selectedText = selObj.toString();

window.getComputedStyle(), window.matchMedia()

The window.getComputedStyle() method accepts an element node as a parameter, and returns an object containing the final style information of the element. For details, see the chapter "CSS Operation".

The window.matchMedia() method is used to check the mediaQuery statement of CSS. For details, see the chapter "CSS Operation".

window.requestAnimationFrame()

The window.requestAnimationFrame() method is similar to setTimeout, both of which postpone the execution of a certain function. The difference is that setTimeout must specify the postponement time, while window.requestAnimationFrame() is postponed until the browser's next re-stream execution, and the next redraw will be performed after execution. Redrawing is usually executed every 16ms, but the browser will automatically adjust this rate. For example, when the web page is switched to the background Tab page, the requestAnimationFrame() will pause execution.

If a function changes the layout of a web page, it is generally executed in window.requestAnimationFrame(), which can save system resources and make the web page effect smoother. Because a slow device will reflow and redraw at a slower rate, and a faster device will have a faster rate.

This method accepts a callback function as a parameter.

window.requestAnimationFrame(callback);

In the above code, callback is a callback function. When callback is executed, its parameter is a high-precision timestamp (the return value of performance.now()) passed in by the system. The unit is milliseconds, which represents the time since the web page is loaded.

The return value of window.requestAnimationFrame() is an integer, which can be passed into window.cancelAnimationFrame() to cancel the execution of the callback function.

The following is an example of window.requestAnimationFrame() executing web page animation.

var element = document.getElementById("animate");
element.style.position = "absolute";

var start = null;

function step(timestamp) {
  if (!start) start = timestamp;
  var progress = timestamp - start;
  // The element keeps moving to the left, no more than 200 pixels
  element.style.left = Math.min(progress / 10, 200) + "px";
  // If the distance from the first execution is not more than 2000 milliseconds,
  // just continue the animation
  if (progress < 2000) {
    window.requestAnimationFrame(step);
  }
}

window.requestAnimationFrame(step);

The above code defines a web page animation with a duration of 2 seconds, which will cause the element to move to the right.

window.requestIdleCallback()

window.requestIdleCallback() is similar to setTimeout, but also postpones the execution of a certain function, but it guarantees to postpone the execution of the callback function until the system resources are free. In other words, if a task is not critical, you can use window.requestIdleCallback() to postpone its execution to ensure web page performance.

The difference between it and window.requestAnimationFrame() is that the latter specifies that the callback function will be executed during the next browser rearrangement. The problem is that the system resources may not be free during the next rearrangement and may not be guaranteed to be completed within 16 milliseconds. ; window.requestIdleCallback() can ensure that the callback function is executed when the system resources are free.

This method accepts a callback function and a configuration object as parameters. The configuration object can specify a maximum time to postpone the execution. If this time passes, the callback function will be executed regardless of whether the system resources are free.

window.requestIdleCallback(callback[, options])

The callback parameter is a callback function. When the callback function is executed, the system will pass in an IdleDeadline object as a parameter. The IdleDeadline object has a didTimeout property (boolean value, indicating whether it is a timeout call) and a timeRemaining() method (returns the number of milliseconds remaining in the idle period).

The options parameter is a configuration object, currently there is only a timeout attribute, which is used to specify the maximum number of milliseconds for the callback function to postpone the execution. This parameter is optional.

The window.requestIdleCallback() method returns an integer. This integer can be passed into the window.cancelIdleCallback() cancel callback function.

Below is an example.

requestIdleCallback(myNonEssentialWork);

function myNonEssentialWork(deadline) {
  while (deadline.timeRemaining() > 0) {
    doWorkIfNeeded();
  }
}

In the above code, requestIdleCallback() is used to perform the non-critical task myNonEssentialWork. The task first confirms that there is remaining time in this idle period, and then it actually starts to execute the task.

The following is an example of specifying timeout.

requestIdleCallback(processPendingAnalyticsEvents, { timeout: 2000 });

The above code specifies that processPendingAnalyticsEvents must be executed within the next 2 seconds.

If the callback function is executed due to timeout, deadline.timeRemaining() returns 0, and deadline.didTimeout returns true.

If you execute window.requestIdleCallback() multiple times and specify multiple callback functions, these callback functions will be arranged in a queue and executed in a first-in first-out order.

Incident

The window object can receive the following events.

load event and onload attribute

The load event occurs when the document is loaded in the browser window. The window.onload property can specify the callback function of this event.

window.onload = function () {
  var elements = document.getElementsByClassName("example");
  for (var i = 0; i < elements.length; i++) {
    var elt = elements[i];
    // ...
  }
};

The above code gets the specified elements and processes them after the web page is loaded.

error event and onerror attribute

When an error occurs in the browser script, the error event of the window object will be triggered. We can specify a callback function for this event through the window.onerror property.

window.onerror = function (message, filename, lineno, colno, error) {
  console.log("Something went wrong!--> %s", error.stack);
};

Due to historical reasons, the callback function of the error event of window does not accept the error object as a parameter, but can accept a total of five parameters, and their meanings are as follows.

-Error message -The URL of the script in error -Line number -Column number -Error object

Old browsers only support the first three parameters.

Not all errors will trigger JavaScript's error event (that is, let JavaScript report an error). Generally speaking, only JavaScript script errors will trigger this event, and errors such as the absence of resource files will not be triggered.

The following is an example, if the entire page has more than 3 uncaught errors, a warning is displayed.

window.onerror = function (msg, url, line) {
  if (onerror.num++ > onerror.max) {
    alert("ERROR: " + msg + "\n" + url + ":" + line);
    return true;
  }
};
onerror.max = 3;
onerror.num = 0;

It should be noted that if the script URL and the web page URL are not in the same domain (for example, when a CDN is used), the browser will not provide detailed error information at all, but will only prompt an error. The error type is "Script error." and the line number is 0, no other information. This is to prevent the browser from leaking information to external scripts. One solution is to set the HTTP header information of Access-Control-Allow-Origin on the server where the script is located.

Access-Control-Allow-Origin: *

Then, set the crossorigin attribute in the <script> tag of the web page.

<script crossorigin="anonymous" src="//example.com/file.js"></script>

The crossorigin="anonymous" in the above code means that no identity information is required to read the file, that is, no cookie and HTTP authentication information are required. If it is set to crossorigin="use-credentials", it means that the browser will upload cookies and HTTP authentication information, and the server side also needs to open the HTTP header Access-Control-Allow-Credentials.

Event monitoring properties of the window object

In addition to the GlobalEventHandlers interface that element nodes have, the window object also has the following event listener function attributes.

-window.onafterprint: listener function for afterprint event. -window.onbeforeprint: listener function for beforeprint event. -window.onbeforeunload: listener function for beforeunload event. -window.onhashchange: listener function for hashchange event. -window.onlanguagechange: Listen function of languagechange. -window.onmessage: listener function for message event. -window.onmessageerror: listener function for MessageError event. -window.onoffline: listener function for offline event. -window.ononline: listener function for online event. -window.onpagehide: listener function for pagehide event. -window.onpageshow: listener function for pageshow event. -window.onpopstate: listener function for popstate event. -window.onstorage: listener function for storage event. -window.onunhandledrejection: The listener function for the reject event of the unhandled Promise object. -window.onunload: listener function for unload event.

Multi-window operation

Because web pages can use the iframe element to embed other web pages, multiple windows are formed in a web page. If another web page is embedded in the child window, a multi-level window will be formed.

Window reference

The script in each window can refer to other windows. The browser provides some special variables to return to other windows.

-top: the top-level window, that is, the top-level window -parent: parent window -self: the current window, which is itself

The following code can determine whether the current window is the top-level window.

if (window.top === window.self) {
  // The current window is the top-level window
} else {
  // The current window is a child window
}

The following code rewinds the visit history of the parent window once.

window.parent.history.back();

Corresponding to these variables, the browser also provides some special window names for reference by the window.open() method, <a> tag, and <form> tag.

-_top: top-level window -_parent: parent window -_blank: new window

The following code means to open the link in the top-level window.

<a href="somepage.html" target="_top">Link</a>

iframe element

For the window embedded in the iframe, the document.getElementById method can get the DOM node of the window, and then use the contentWindow property to get the window object contained in the iframe node.

var frame = document.getElementById("theFrame");
var frameWindow = frame.contentWindow;

In the above code, frame.contentWindow can get the window object of the child window. Then, if the homology restriction is met, the attributes inside the sub-window can be read.

// Get the title of the child window
frameWindow.title;

The contentDocument attribute of the <iframe> element can get the document object of the child window.

var frame = document.getElementById("theFrame");
var frameDoc = frame.contentDocument;

// Equivalent to
var frameDoc = frame.contentWindow.document;

The <iframe> element complies with the same-origin policy. Only when the parent window and the child window are in the same domain, the script communication can be used between the two, otherwise only the window.postMessage method can be used.

Inside the <iframe> window, use window.parent to refer to the parent window. If the current page does not have a parent window, the window.parent property returns itself. Therefore, you can determine whether the current window is an iframe window by whether window.parent is equal to window.self.

if (window.parent !== window.self) {
  // The current window is a child window
}

The window object of the <iframe> window has a frameElement property, which returns the DOM node of the <iframe> in the parent window. For non-embedded windows, this property is equal to null.

var f1Element = document.getElementById("f1");
var f1Window = f1Element.contentWindow;

f1Window.frameElement === f1Element; // true
window.frameElement === null; // true

window.frames property

The window.frames property returns an array-like object, the member is the window object of all child windows. You can use this attribute to achieve mutual reference between windows. For example, frames[0] returns the first child window, frames[1].frames[2] returns the third child window inside the second child window, and parent.frames[1] returns the parent window The second child window.

Note that the value of each member of window.frames is the window within the frame (ie the window object of the frame), not the DOM node of the parent window where the iframe tag is located. If you want to get the DOM tree inside each frame, you need to use the wording of window.frames[0].document.

In addition, if the name or id attribute is set on the <iframe> element, the attribute value will automatically become a global variable and can be referenced by the window.frames attribute to return the window object of the child window.

// HTML code is <iframe id="myFrame">
window.myFrame; // [HTMLIFrameElement]
frames.myframe === myFrame; // true

In addition, the value of the name attribute will automatically become the name of the child window, which can be used in the second parameter of the window.open method, or the target attribute of the <a> and <frame> tags.