This is the 14th day of my participation in Gwen Challenge

1. An overview of the

The Window object refers to the current browser window, which is also the top level object of the current page, with all other objects subordinate to it. A variable that is not declared is a property of the top-level object by default.

// a is an undeclared variable that automatically becomes a property of the top-level object.
a = 1;
console.log(window.a) / / 1
Copy the code

Window has its own entity meaning and is not really suitable as a top-level object at the highest level, which is a language design error. When the language was first designed, it was supposed to have as few built-in objects as possible to improve browser performance. Therefore, language designer Brendan Eich treated the Window object as a top-level object, and all undeclared variables assigned values automatically became properties of the window object. This design makes it impossible to detect undeclared variables at compile time, but today there is no way to correct this.

2. Properties of the window object

2.1 Window.name The window.name property is a string representing the name of the current browser window. The window doesn’t have to have a name; this property works with hyperlinks and the target property of the form.

window.name = 'Hello World! ';
console.log(window.name) // "Hello World!"
Copy the code

This property can only hold strings and is automatically converted to strings if the value written is not a string. This property does not disappear as long as the browser window is not closed. For example, when you visit a.com, the script on the page is set window.name, and then b.com is loaded in the same window. The script on the new page reads window.name from the previous page. The same is true for page refreshes. Once the browser window is closed, the value saved by this property disappears because the window no longer exists.

2.2 Windows closed, the window opener

The window.closed attribute returns a Boolean value indicating whether the window is closed.

window.closed // false
Copy the code

The above code checks if the current window is closed. This check doesn’t make much sense, because as long as the code is running, the current window is definitely not closed. This property is typically used to check whether a new window opened with the script is closed.

var popup = window.open();
if((popup ! = =null) && !popup.closed) {
	// The window remains open
}
Copy the code

2.2.2 Window. opener property indicates that the parent window of the current window is opened. Returns NULL if the current window does not have a parent window (that is, it is opened by typing directly into the address bar).

// The expression opens a new window and returns true
window.open().opener === window // true
Copy the code

If the two Windows do not need to communicate, it is recommended that the opener property of the sub-window be explicitly set to NULL to reduce some security risks.

// If the opener property is set to null, there will be no contact between the two Windows
var newWin = window.open('example.html'.'newWindow'.'height=400,width=400');
newWin.opener = null;
Copy the code

Through the opener attribute, the global attribute and method of the parent window can be obtained, but only in the case of the same origin of two Windows, and one window is opened by the other. The < a > element adds the rel=”noopener” attribute to prevent newly opened Windows from getting the parent window, reducing the risk of malicious websites modifying the parent window URL.

<a href="https://an.evil.site" target="_blank" rel="noopener"> </a>Copy the code

Self, window.window window.self, and window.window all point to the window itself, and these two properties are read-only

console.log(window.self === window) // true
console.log(window.window === window) // true
Copy the code

The frames, window.length window.frames property returns an array-like object containing all frame Windows on the page, including frame elements and iframe elements. Window.frames [0] represents the first frame window in the page.

If the iframe element has an ID or name attribute, then the iframe window can be referenced with the attribute value. < iframe name=”myIFrame”> can be referenced by frames[‘myIFrame’] or frames. MyIFrame.

The Frames attribute is actually an alias for the Window object.

frames === window // true
Copy the code

Therefore, frames[0] can also be represented as window[0]. Frames are semantically clearer, and given that a window is a global object, it is always recommended to write frames[0] for multiple Windows. The window.length property returns the total number of frames contained in the current web page. If the current page does not contain frame and iframe elements, window.length returns 0.

// window.frames. Length should be equal to window.length
window.frames.length === window.length // true
Copy the code

The window.frameElement attribute is used when the current window is embedded in another web page (embed an < object >, < iframe >, or < embed > element) and returns the element node where the current window is located. This property returns NULL if the current window is a top-level window, or if the embedded web page is not cognate.

// The 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';
}
Copy the code

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

2.6 Window. top, window.parent Window. top Refers to the top-level window, which is used to obtain the top-level window in the frame window. The window.parent property points to the parent window. If the current window has no parent, window.parent points to itself; For web pages that do not contain frames, these two properties are equivalent to the Window object

if (window.parent ! = =window.top) {
  // Indicates that the current window is embedded at more than one level
}
Copy the code

2.7 Window.status The window.status property is used to read and write text in the browser status bar. Note: Many browsers don’t allow you to rewrite status bar text, so using this method may not work.

DevicePixelRatio The devicePixelRatio property returns a number representing the ratio of the size of a CSS pixel to the size of a physical pixel. It indicates how many physical pixels a CSS pixel is made up of. It can be used to determine the user’s display environment, and if the ratio is high, it indicates that the user is using a high-definition screen and therefore can display larger pixels of images.

3. Location size properties

The window.screenX and window.screenY properties return the horizontal and vertical distances (in pixels) of the top left corner of the browser window relative to the top left corner of the current screen.

The window.innerHeight and window.innerWidth properties return the height and width of the visible portion of the page in the current window. This is the size of the viewport in pixels.

These properties become smaller when users zoom in on a web page (say, from 100% to 200%). The pixels on the page are the same size (say, 960 pixels wide), but each pixel takes up more screen space because the visible portion (viewport) is smaller.

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

OuterHeight, window.outerWidth (read only) The window.outerHeight and window.outerWidth properties return the height and width of the browser window, including the browser menu and border in pixels.

The window.scrollX property returns the horizontal scrolling distance of the page, and the window.scrollY property returns the vertical scrolling distance of the page, both in pixels.

Note: The return value of these two properties 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 75 pixels, window.scrolly is about 75 pixels. The user horizontally pulls the horizontal scroll bar 200 pixels to the right, so window.scrollx is about 200 pixels.

// If the page scrolls down less than 75 pixels, then the page scrolls down 75 pixels
if (window.scrollY < 75) {
  window.scroll(0.75);
}
Copy the code

3.5 Window. pageXOffset, window.pageYOffset Window. pageXOffset and window.pageYOffset are aliases for window.scrollX and window.scrollY.

4. Component properties

Component properties return the component object of the browser.

window.locationbar // Address bar object
window.menubar  // Menu bar object
window.scrollbars // The window scroll bar object
window.toolbar // Toolbar object
window.statusbar // Status bar object
window.personalbar // The personal toolbar object installed by the user
Copy the code

The visible property of these objects is a Boolean value indicating whether the components are visible. These properties are read-only.

window.locationbar.visible
window.menubar.visible
window.scrollbars.visible
window.toolbar.visible
window.statusbar.visible
window.personalbar.visible
Copy the code

5. Global object properties

The global object property points to some browser-native global objects.

window.document  // Point to the document object. Note that this property has a homology constraint. Only scripts from the same origin can read this property.
window.location  // Points to the Location object to get the URL information for the current window. It is equivalent to the document.location property.
window.navigator  // Point to the Navigator object to get environment information.
window.history  // Point to the History object, which represents the browser's browsing History.
window.localStorage  // Point to localStorage data stored locally.
window.sessionStorage  // Point to sessionStorage data stored locally.
window.console  // Points to the console object, used to manipulate the console.
window.screen  // Point to the Screen object, representing Screen information.
window.isSecureContext  // Property returns a Boolean value indicating whether the current window is in an encrypted environment. True if HTTPS is used, false otherwise.
Copy the code

6. Window object methods

6.1 Window.alert (), window.prompt(), window.confirm() these three methods all have blocking effect. Once the dialog box pops up, the execution of the whole page is suspended, waiting for the user to react.

The window.alert() method brings up a dialog box with a single “OK” button, often used to notify the user of certain information. The dialog box will disappear only if the user clicks the “OK” button. During the pop-up dialog, the browser window freezes, and the user can’t do anything without clicking ok. The window.alert() method can only take strings and cannot use CSS styles, but newlines can be specified with \n.

window.alert('Hello World');
alert('This tip \n divided into two lines');
Copy the code

The window.prompt() method displays a dialog box with an input box below the text that asks the user to enter information and has two buttons: OK and Cancel. The second argument to the window.prompt() method is optional, but it is always a good idea to provide the second argument as the default value for the input field. It is often used to retrieve user input data.

// The code will pop up with a dialog box asking "How old are you? ", asking the user to enter their age in the dialog box (25 is displayed by default). The value that the user fills in is stored in the result variable as the return value.
var result = prompt('How old are you? '.25)
console.log(result)
Copy the code

The window.prompt() return value can be either a string (which can be an empty string) or null. It can be divided into three cases:

  1. The user enters the information and clicks “OK”, the information entered by the user is the return value.
  2. If the user clicks “OK” without input information, the default value of the input box is the returned value.
  3. When the user hits Cancel (or presses the ESC button), the return value is null.

The window.confirm() method displays a dialog box with only “CONFIRM” and “cancel” buttons in addition to the prompt message, which is usually used to ask the user whether to agree or not. The Confirm method returns a Boolean value, true if the user clicks OK; If the user clicks Cancel, false is returned.

var okay = confirm('Please confirm this message.');
if (okay) {
  // User presses "OK"
} else {
  // User presses cancel
}
Copy the code

One use for Confirm is that when the user leaves the current page, a dialog box pops 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? ');
}
Copy the code

6.2 window. The open () the window. The close (), window. The stop ()

The window.open() method is used to create another browser window, similar to the New window option in the browser menu. It returns a reference to the new window, or null if it cannot be created.

// the browser pops up a new window and the url is somefile.html under the current domain name
var popup = window.open('somefile.html');
Copy the code

The open method can take three arguments in total:

window.open(URL, windowName, [windowFeatures]) URL: a string indicating 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 a window with this name already exists, the window is occupied and no new window is created. If omitted, the default is _blank, which means that a new window without a name is created. There are also several preset values, _self for the current window, _top for the top-level window, and _parent for the next-level window. WindowFeatures: A string of comma-separated key-value pairs (as listed below) that represent parameters for the new window, such as prompt bars, toolbars, and so on. If omitted, a full new window opens by default. If you create an existing window, this parameter has no effect and the browser uses the same parameters as the previous window. The third parameter can be set to the following properties: left: The distance (in pixels) of the new window from the left-most part of the screen. Note that the new window must be visible and cannot be set off-screen. Top: Distance (in pixels) from the top of the screen to the new window. Height: The height (in pixels) of the content area of the new window100. Width: the width (in pixels) of the content area of the new window, not less than100. OuterHeight: The height (in pixels) of the entire browser window100. OuterWidth: The width (in pixels) of the entire browser window100. Menubar: indicates whether to display the menubar. Toolbar: Whether to display a toolbar. Location: Indicates whether to display the address bar. Personalbar: Whether the toolbar installed by the user is displayed. Status: Indicates whether to display the status bar. Dependent: whether to rely on the parent window. If dependent, then the parent window is minimized and so is the window; The parent window closes and the window closes. Minimizable: Whether there is a minimize button, provided dialog=yes. Noopener: The new window will be disconnected from the parent window, that is, the new windowwindowThe.opener property returnsnullParent windowwindowThe.open() method also returnsnull. Resizable: Whether the new window can be resized. Scrollbars: Whether to allow scrollbars in new Windows. Dialog: Whether the new window title bar appears to maximize, minimize, restore the original size of the control. Titlebar: whether the new window displays a titlebar. AlwaysRaised: Whether it is displayed at the top of all Windows. AlwaysLowered: Whether to display at the bottom of the parent window. Close: Indicates whether the close button is displayed in the new window. For properties that can be turned on and off, set it to yes or1Or no value is set to open; For example, status=yes, status=1And Status get the same result. If you want to set it to off, instead of writing no, you can simply omit this property. If part of the third parameter is set, all other yes/no attributes that are not set are set to no. The exceptions are the Titlebar and the close button (which default to yes).Copy the code
// A new window opens with a height and width of 200 pixels, no address bar, but a status bar and scroll bar that allows the user to resize.
var popup = window.open(
  'somepage.html'.'DefinitionsWindows'.'height=200,width=200,location=no,status=yes,resizable=yes,scrollbars=yes'
);
Copy the code

The second argument to the open() method, while specifying existing Windows, does not give you arbitrary control over other Windows. To prevent control by unrelated Windows, the browser only allows the open method to point to the window if the two Windows are the same origin, or if the target window is opened by the current web page.

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

var windowB = window.open('windowB.html'.'WindowB');
windowB.window.name // "WindowB"
Copy the code

Note: If the new window and parent window are not homologous (that is, not in the same domain), they cannot obtain the internal properties of each other’s window objects.

// Open a new window and pop up a dialog box in that window to direct the url to example.com
var w = window.open();
console.log('New window already opened');
w.location = 'http://example.com';
Copy the code

Because the open method can be easily abused, many browsers don’t allow scripts to automatically create new Windows by default. Only allow the script to react and pop up a new window when the user clicks a link or button. Therefore, it is worth checking to see if the new window was opened successfully.

var popup = window.open();
if (popup === null) {
  // Failed to create a window
}
Copy the code

The window.close() method is used to close the current window, usually only Windows created by the window.open method. This method only works for top-level Windows, not Windows in the iframe framework.

window.close()
Copy the code

The window.stop() method is exactly the same as clicking the browser’s stop button, which stops loading images, videos, and other objects that are loading or waiting for loading.

window.stop()
Copy the code

6.3 Window.moveto (), window.resizeby () Note: In order to prevent someone from abusing these two methods by moving the user’s window at will, there is currently only one case where the browser allows scripting to move the window: The window is created using the window.open method, and the Tab page it is on is the only one in the current window. In other cases, the above two methods are ineffective.

The window.moveto () method is used to move the browser window to the specified position. It takes two parameters, the horizontal distance between the top left corner of the window and the top left corner of the screen, and the vertical distance, in pixels.

// Move the window to the screen position (100, 200)
window.moveTo(100.200)
Copy the code

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

// Move the window 25 pixels to the right and 50 pixels down
window.moveBy(25.50)
Copy the code

6.4 Window.scrollto (), window.scroll(), window.scrollby ()

The window.scrollto () method is used to scroll the document to the specified location. Accepts two parameters that represent the page coordinates in the upper-left corner of the window after scrolling.

window.scrollTo(x-coord, y-coord)
Copy the code

You can also accept a configuration object as a parameter.

window. ScrollTo (options) The options configuration object has three properties: Top: indicates the vertical coordinate of the upper left corner of the page after scrolling, that is, the Y coordinate. Left: horizontal coordinate of the upper left corner of the page after scrolling, that is, x coordinate. Behavior: A string representing the scrolling mode with three possible values (smooth, instant, and auto). The default value is auto.window.scrollTo({
  top: 1000.behavior: 'smooth'
});
Copy the code

The window.scroll() method is an alias for the window.scrollto () method.

The window.scrollby () method is used to scroll the web page a specified distance in pixels. It takes two parameters: a pixel that scrolls horizontally to the right and a pixel that scrolls vertically down.

// Scroll the page down one screen
window.scrollBy(0.window.innerHeight)
Copy the code
If you want to scroll an Element instead of the entire document, you can use the following three properties and methods: element.scrollTop Element.scrollLeft element.scrollintoView ()Copy the code

6.5 Window.print () Window.print () the window.print() method displays the print dialog box, which has the same effect as when the user clicks the “print” command in the menu.

// The common print button code is as follows
document.getElementById('printLink').onclick = function () {
  window.print();
}
Copy the code
// Non-desktop devices (such as mobile phones) may not have printing capabilities
if (typeof window.print === 'function') {
  // Support printing function
}
Copy the code

6.6 Window.focus (), window.blur() Window.focus () the window.blur() method activates the window so that it gets focus and appears in front of other Windows.

// Check that the popUp window still exists and activate it
var popup = window.open('popup.html'.'Popup Window');

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

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

The focus event is emitted when the current window gets focus. The Blur event is triggered when the current window loses focus.

6.7 Window.getSelection () The window.getSelection method returns a Selection object representing the text that the user is currently selecting.

var selObj = window.getSelection();
// Use the toString method for Selection to get the selected text
var selectedText = selObj.toString();
Copy the code

6.8 Windows. GetComputedStyle (), window. MatchMedia ()

The window.getComputedStyle() method takes an element node as an argument and returns an object containing the final style information for that element. The window.matchmedia () method checks CSS mediaQuery statements.

6.9 Windows. RequestAnimationFrame ()

Window. RequestAnimationFrame with setTimeout () method is similar, are delay the execution of a function. The difference is: setTimeout must specify the delay time, the window. The requestAnimationFrame browser () is delayed until the next heavy flow execution, execution of the will to redraw next time. Redraw is typically performed at a rate of 16ms, but the browser adjusts this rate automatically, such as requestAnimationFrame() pausing when the page switches to a background Tab.

If a function to change the layout of the page, usually on the window. The requestAnimationFrame (), so I can save system resources, make the site more smooth. This is because slower devices will restream and redraw at a slower rate, while faster devices will have a faster rate.

window.requestAnimationFrame(Callback) Callback is a callback function. When the callback is executed, its argument is a high-precision timestamp passed in by the system (the return value of performing.now ()), in milliseconds, representing the time since the page was loaded.windowThe return value of.requestAnimationFrame() is an integer that can be passed inwindow.cancelAnimationFrame(), which cancels the execution of the callback function.Copy the code
. / / the following is a window requestAnimationFrame () example of web animation duration is 2 seconds, will let the elements to the right.
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 moves continuously to the left, up to a maximum of 200 pixels
  element.style.left = Math.min(progress / 10.200) + 'px';
  // If it is not more than 2000 milliseconds since the first execution,
  // Continue with the animation
  if (progress < 2000) {
    window.requestAnimationFrame(step); }}window.requestAnimationFrame(step);
Copy the code

6.10 Windows. RequestIdleCallback () the window. The requestIdleCallback with setTimeout (), is also a function will be put off, but it guarantees the callback function will be put off to the execution system resources is idle. That is to say, if a task is not the key, you can use the window. The requestIdleCallback () to delay the execution, to ensure that the web performance.

It with window. RequestAnimationFrame () : the difference between the specified callback function execution when the next browser rearrangement, the problem is that the next rearrangement, system resources may not free, not necessarily can ensure the completion within 16 milliseconds; Window. RequestIdleCallback () can guarantee the callback function in the system resources is idle.

windowThe.requesTidlecallBack (callback[, options]) callback argument is a callback function. When this callback is executed, an IdleDeadline object is passed as an argument. The IdleDeadline object has a didTimeout attribute (a Boolean value indicating whether it is a timeout call) and a timeRemaining() method that returns the number of milliseconds remaining in the idle period. The options parameter is a configuration object. Currently, only a timeout property is used to specify the maximum number of milliseconds the callback function can delay execution. This parameter is optional.windowThe.requestidlecallback () method returns an integer that can be passed inwindow.cancelidlecallBack () cancels the callback function.Copy the code
// requestIdleCallback() is used to perform non-critical tasks myNonEssentialWork. Before performing the task, ensure that the idle period is available
requestIdleCallback(myNonEssentialWork);

function myNonEssentialWork(deadline) {
  while (deadline.timeRemaining() > 0) { doWorkIfNeeded(); }}Copy the code
/ / processPendingAnalyticsEvents must be carried out in the next two seconds
requestIdleCallback(processPendingAnalyticsEvents, { timeout: 2000 });
Copy the code

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

If multiple Windows. RequestIdleCallback (), specify multiple callback function, then the callback function will be arranged in a queue, in the order in accordance with the first-in, first-out.

7. Events

The window object can receive the following events

The window.onload attribute specifies a callback function for the load event that occurs when the document is loaded in the browser window.

// After the page is loaded, get the specified element and process it
window.onload = function() {
  var elements = document.getElementsByClassName('example');
  for (var i = 0; i < elements.length; i++) {
    var elt = elements[i];
    // ...}};Copy the code

7.2 Error Event and onError Attribute When an error occurs in the browser script, the error event of the Window object will be raised. You can specify a callback function for this event through the window.onerror attribute.

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

windowInstead, it can take a total of five arguments: the error message, the url of the error script, the line number, the column number, and the error object. Older browsers only support the first three arguments. Not all errors raise JavaScript error events. In general, only JavaScript script errors will trigger this event, not errors such as the nonexistence of resource files.Copy the code
If the entire page does not catch more than 3 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;
Copy the code

Note: if the Script url and the web url are not in the same domain (for example, using CDN), the browser will not provide detailed error information at all, only the error type is “Script error.”, the line number is 0, and there is no other information. This prevents the browser from leaking information to external scripts. One solution is to set the ACCESS-Control-Allow-Origin HTTP header on the server where the script resides:

Access-Control-Allow-Origin: *
// Set the Crossorigin attribute in the 
<script crossorigin="anonymous" src="//example.com/file.js"></script>Crossorigin = of the code above"anonymous"Indicates that no identity information is required to read a file, that is, cookies and HTTP authentication information are not required. If I set it to crossorigin="use-credentials"Indicates that the browser uploads cookies and HTTP authentication information, and the HTTP header access-Control-allow-credentials need to be enabled on the server.Copy the code

7.3 Event listening properties of window Objects

window.onafterprint  // AfterPrint event listener function.
window.onbeforeprint  // beforePrint event listener function.
window.onbeforeunload  // beforelistener functions for unload events.
window.onhashchange  // A listener for the hashchange event.
window.onlanguagechange  // Listen to languagechange.
window.onmessage  // Message event listener function.
window.onmessageerror // a listener for MessageError.
window.onoffline  // Offline event listener function.
window.ononline  // online event listener function.
window.onpagehide  // pageHide event listener function.
window.onpageshow  // The pagesHow event listener function.
window.onpopstate  // The popState event listener function.
window.onstorage  // Storage event listener function.
window.onunhandledrejection  // A listener for the reject event of the unprocessed Promise object.
window.onunload  // Listener function for unload events.
Copy the code

8. Multi-window operation

Because web pages can embed iframe elements into other web pages, multiple Windows can form within a web page. If the child window is embedded in other pages, it will form a multi-level window. 8.1 References to Windows Scripts in each window can refer to other Windows. The browser provides some special variables to return to other Windows.

  1. Top: the top window, the top window;
  2. Parent: parent window;
  3. Self: the current window, itself;
// Check 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
}

// Check whether the current window is the top-level window
window.parent.history.back();
Copy the code

Corresponding to these variables, browsers provide special window names that are referenced by the window.open() method, the < a > tag, the < form > tag, and so on.

  1. _top: indicates the top-level window.
  2. _parent: parent window;
  3. _blank: New window;
// Open the link in the top-level window
<a href="somepage.html" target="_top">Link</a>
Copy the code

For embedded Windows, the document.getElementById method gets the DOM node of the window and uses the contentWindow property to get the window object contained in the iframe node.

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

// In the code above, frame.contentWindow gets the window object of the child window.
// Then, subject to the same origin restriction, the attributes inside the child window can be read.
// Gets the title of the child window
frameWindow.title
Copy the code

The contentDocument property of the < iframe > element takes the document object of the child window.

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

/ / is equivalent to
var frameDoc = frame.contentWindow.document;
Copy the code

The < iframe > element complies with the same origin policy, and script communication between the parent window and child window is possible only if the two are in the same domain, otherwise only the window.postMessage method is used.

<iframe> inside the window, usedwindow.parent references the parent window. If the current page does not have a parent windowwindowThe.parent property returns itself. Therefore, it can be passedwindow.parent Is equal towindow.self, checks whether the current window is an iframe window.if (window.parent ! = =window.self) {
  // The current window is a child window} <iframe> windowwindowObject with a frameElement attribute that returns the DOM node <iframe> in the parent window. For non-embedded Windows, this property is equal tonull.var f1Element = document.getElementById('f1');
var f1Window = f1Element.contentWindow;
f1Window.frameElement === f1Element // true
window.frameElement === null // true
Copy the code

The window.frames attribute returns an array-like object whose members are the window objects of all child Windows. You can use this property to implement cross-references 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 second child window of the parent window.

Note: Window. frames is the value of each member of the window within the frame (that is, the window object of the frame), not the DOM node of the parent window. To get the DOM tree inside each frame, use window.frames[0].document.

If the <iframe> element has a name or ID attribute, the attribute value automatically becomes a global variable that can be passedwindowThe.frames attribute reference returns the value of the child windowwindowObject.
window.myFrame // [HTMLIFrameElement]
frames.myframe === myFrame // trueThe value of the name attribute automatically becomes the name of the child window, which can be used inwindowThe second argument to the.open method, or the target property of the <a> and <frame> tagsCopy the code