This is the 7th day of my participation in the August More Text Challenge

The window object

An overview of the

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 top level object, and all other objects are subordinate to it. A variable that is not declared is a property of the top-level object by default.

a = 1;
window.a / / 1
Copy the code

In the code above, a is an undeclared variable assigned directly, which automatically becomes a property of the top-level object.

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.

globalThis

ES11 introduces globalThis, which is used to align with NodeJS, globalThis === window in the browser and glovalThis === global in nodeJS

Property of the window object

window.name

The window.name attribute is a string that represents 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. The storage capacity for this value varies from browser to browser, but in general, it can be up to a few megabytes.

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.

The window 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

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

window.open().opener === window // true
Copy the code

The above expression opens a new window and returns true.

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.

var newWin = window.open('example.html'.'newWindow'.'height=400,width=400');
newWin.opener = null;
Copy the code

In the above code, the opener property of the child window is set to null, so the two Windows can no longer contact each other.

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 (see chapter “Same Origin Restriction”), and one window is opened by the other. The 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 malicious web site</a>
Copy the code

The window. The self, the window. The window

The window.self and window.window properties both point to the window itself. These two properties are read-only.

window.self === window // true
window.window === window // true
Copy the code

The window frames, window length

The window.frames property returns an array-like object containing all frame Windows on the page, including the frame element and the iframe element. 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. For example,

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]. However, frames are semantically clearer, and given that a window is a global object, it is always recommended to write frames[0] for multiple Windows. See multi-window operations below for more information.

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 === window.length // true
Copy the code

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

window.frameElement

The window.frameElement attribute is used when the current window is embedded in another web page (embed an ,

// 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

Window. The top window. The parent

The window.top property refers to the top-level window and is used to retrieve the top-level window within a frame window.

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

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

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 text from the browser status bar. However, many browsers don’t allow you to rewrite the status bar text, so using this method may not work.

window.devicePixelRatio

The window.devicePixelRatio property returns a number representing the ratio of the size of a CSS pixel to the size of a physical pixel. That is, it represents 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.

Position size attribute

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

(1) Window.screenx, window.screeny

The window.screenx and window.screeny properties return the horizontal and vertical distances in pixels from the top left corner of the browser window to the top left corner of the current screen. These two properties are read-only.

(2) window.innerHeight, window.innerWidth

The window.innerHeight and window.innerWidth properties return the height and width of the visible portion of the web page in the current window, which is the size in pixels of the viewport. These two properties are read-only.

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, so the visible portion (viewport) becomes smaller.

Note that these two property 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 properties are read-only.

(4) window.scrollX, window.scrollY

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. These two properties are read-only.

Notice that 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 (window.scrollY < 75) {
  window.scroll(0.75);
}
Copy the code

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

(5) window.pageXOffset, window.pageYOffset

The window.pageXOffset and window.pageYOffset properties are aliases for window.scrollX and window.scrollY.

Component attributes

Component properties return the component object of the browser. There are several such properties.

  • window.locationbar: Address bar object
  • window.menubar: menu bar object
  • window.scrollbars: scroll bar object of a 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 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

Global object properties

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

  • window.document: point todocumentObject, see the Chapter document Object. Note that this property has a homology constraint. Only scripts from the same origin can read this property.
  • window.location: point toLocationObject to get the URL information for the current window. It is equivalent todocument.locationProperties, as described in the Chapter Location Object.
  • window.navigator: point toNavigatorObject for retrieving environment information, as described in the Navigator Object chapter.
  • window.history: point toHistoryObject, representing the browsing History of the browser. For details, see the chapter History Object.
  • window.localStorage: indicates the localStorage data. For details, see section Storage interface.
  • window.sessionStorage: indicates local Storage sessionStorage data. For details, see Section Storage Interface.
  • window.console: point toconsoleObject used to operate the console, as described in the Console Object chapter.
  • window.screen: point toScreenObject represents Screen information. For details, see the chapter Screen Objects.

window.isSecureContext

The window.isSecureContext property returns a Boolean value indicating whether the current window is in an encrypted environment. True if HTTPS is used, false otherwise.

Window object method

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 pop up different dialogs asking the user to respond. Note that these three methods pop up dialog boxes, browser uniform style, cannot be customized.

(1) the window. The alert ()

The window.alert() method brings up a dialog box with a single “OK” button, often used to notify the user of certain information.

window.alert('Hello World');
Copy the code

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.

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

(2) the window. The prompt ()

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. It is often used to retrieve user input data.

var result = prompt('How old are you? '.25)
Copy the code

The code will pop up with a dialog 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.

The window.prompt() return value can be either a string (which can be an empty string) or null. Specifically 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 isnull.

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.

(3) the window. Confirm ()

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.

var result = confirm('How have you been? ');
Copy the code

The code above pops up a dialog box with just the words “How are you?” , the user can choose to click “OK” or “Cancel”.

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

All three of these methods have a blocking effect, and as soon as a dialog pops up, the entire page pauses while the user reacts.

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

(1) the window. The open ()

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.

var popup = window.open('somefile.html');
Copy the code

The code above will cause the browser to pop up a new window with the url somefile.html under the current domain name.

The open method can take three arguments in total.

window.open(url, windowName, [windowFeatures])
Copy the code
  • url: a string representing the url of the new window. If omitted, the default url isabout:blank.
  • windowName: indicates 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, it is used by default_blankTo create a window without a name. There are also several presets,_selfRepresents the current window,_topRepresents the top-level window,_parentRepresents the previous window.
  • windowFeatures: a string of comma-separated key-value pairs (see below) that represent parameters for the new window, such as prompt bars, toolbars, and so on. If omitted, a new window of the full UI 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.

Here’s an example.

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

The code above shows that the new window opens 200 pixels high and wide, with no address bar but a status bar and a scrollbar that allows the user to resize.

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 window, not less than 100.
  • Width: The width (in pixels) of the content area of the new window, not less than 100.
  • OuterHeight: The height of the entire browser window in pixels, not less than 100.
  • OuterWidth: The width of the entire browser window in pixels, not less than 100.
  • 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 ifdialog=yes.
  • Noopener: The new window will be disconnected from the parent window, that is, the new windowwindow.openerProperty returnsnullParent windowwindow.open()The 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, setting it to yes or 1 or no value at all, such as status=yes, status=1, and status, gives the same result. If you want to set it to off, instead of writing no, you can simply omit this property. That is, if part of the property is set in the third argument, all the other yes/ NO properties that are not set are set to no, except the titlebar and the close button (which default to Yes).

The above attributes are connected by an equal sign between their names and values, and separated by commas.

'height=200,width=200,location=no,status=yes,resizable=yes,scrollbars=yes'
Copy the code

In addition, the second argument to the open() method can specify existing Windows, but 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 that if the new window and the parent window are not homologous (that is, not in the same domain), they cannot obtain the internal properties of each other’s window objects.

Here’s another example.

var w = window.open();
console.log('New window already opened');
w.location = 'http://example.com';
Copy the code

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

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

(2) the window. The close ()

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

popup.close()
Copy the code

This method only works for top-level Windows, not Windows in the iframe framework.

(3) the window. The stop ()

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

Window. The moveTo (), window. MoveBy ()

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.

window.moveTo(100.200)
Copy the code

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

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

window.moveBy(25.50)
Copy the code

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

To prevent someone from abusing these two methods and moving a user’s window around, the browser currently only allows scripting to move a window if it is created using the window.open() method and has only one Tab page in the window. In other cases, the above two methods are ineffective.

Window. ResizeTo (), window. ResizeBy ()

The window.resizeto () method is used to scale the window to a specified size.

It takes two arguments, the first is the zoomed window width (the outerWidth property, which contains the scrollbar, title bar, and so on) and the second is the zoomed window height (the outerHeight property).

window.resizeTo(
  window.screen.availWidth / 2.window.screen.availHeight / 2
)
Copy the code

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

The window.resizeby () method is used to scale the window. The difference between it and window.resizeto () is that it scales in relative quantities. Window.resizeto () needs to give the absolute size after scaling.

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

window.resizeBy(-200, -200)
Copy the code

The code above 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 location. It takes 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

It can also take a configuration object as a parameter.

window.scrollTo(options)
Copy the code

The configuration object Options has three properties.

  • top: Vertical coordinate of the upper left corner of the page after scrolling, that is, y coordinate.
  • left: Horizontal coordinate of the upper left corner of the page after scrolling, that is, the X coordinate.
  • behavior: a string representing the mode of scrolling with three possible values (smooth,instant,auto), the default value isauto.
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.

window.scrollBy(0.window.innerHeight)
Copy the code

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

If you want to scroll an element rather than the entire document, you can use the following three properties and methods.

  • Element.scrollTop
  • Element.scrollLeft
  • Element.scrollIntoView()

window.print()

The window.print method displays the print dialog box, the same effect as when the user clicks the “print” command in the menu.

Common print button codes are as follows.

document.getElementById('printLink').onclick = function () {
  window.print();
}
Copy the code

If a non-desktop device (such as a mobile phone) does not have printing capability, you can tell by this.

if (typeof window.print === 'function') {
  // Support printing function
}
Copy the code

Window. The focus (), the window. The blur ()

The window.focus() method activates the window so that it gets focus and appears in front of other Windows.

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

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

The above code first checks to see if the popUp window still exists and then activates it.

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.

window.getSelection()

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

var selObj = window.getSelection();
Copy the code

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

var selectedText = selObj.toString();
Copy the code

Window. GetComputedStyle (), window. MatchMedia ()

The window.getComputedStyle() method takes an element node as an argument and returns an object containing the element’s final style information, as described in the CSS Operations chapter.

The window.matchmedia () method is used to check CSS mediaQuery statements, as described in CSS Operations.

window.requestAnimationFrame()

Window. RequestAnimationFrame with setTimeout () method is similar, are delay the execution of a function. The difference is that 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.

This method takes a callback function as an argument.

window.requestAnimationFrame(callback)
Copy the code

In the above code, 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.

Window. RequestAnimationFrame () of the return value is an integer, the integer can be introduced into the window. The cancelAnimationFrame (), is used to cancel the execution of the callback function.

Here is a window. RequestAnimationFrame () example of web 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 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

The code above defines a web page animation that lasts 2 seconds and moves the element to the right.

window.requestIdleCallback()

Window. 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 () difference is that the latter specifies a callback function 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.

This method takes a callback function and a configuration object as parameters. The configuration object can specify a maximum period of time after which the callback will be executed regardless of whether system resources are free.

window.requestIdleCallback(callback[, options])
Copy the code

The 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 that currently only has a timeout property, which specifies the maximum number of milliseconds that the callback function can delay execution. This parameter is optional.

Window. RequestIdleCallback () method returns an integer. The integer can be introduced into the window. CancelIdleCallback () cancel the callback function.

Here’s an example.

requestIdleCallback(myNonEssentialWork);

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

In the code above, requestIdleCallback() is used to perform the non-critical task myNonEssentialWork. Before performing the task, ensure that the idle period is available.

Here is an example of specifying a timeout.

requestIdleCallback(processPendingAnalyticsEvents, { timeout: 2000 });
Copy the code

Code specified above, processPendingAnalyticsEvents must be carried out in the next two seconds.

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.

The event

The window object can receive the following events.

Load event and onLoad attribute

The load event occurs when the document is finished loading in the browser window. The window.onload property specifies the event callback function.

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

The code above gets the specified element and processes it after the page is loaded.

Error events and onError properties

The error event of the window object is raised when the browser script fails. We can specify a callback function for this event via the window.onerror property.

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

For historical reasons, the window’s error event callback does not take an error object as an argument. Instead, it can take a total of five arguments, each of which has the following meanings.

  • An error message
  • The url of the error script
  • The line Numbers
  • Column number
  • Error object

Older browsers only support the first three parameters.

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.

Here is an example that displays a warning if the entire page does not catch more than 3 errors.

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

It should be noted that if the Script URL and the web url are not in the same domain (for example, CDN is used), the browser will not provide detailed error information at all, only an error message, the error type is “Script Error.”, the line number is 0, and no other information. This prevents the browser from leaking information to external scripts. One solution is to set the HTTP header for Access-Control-Allow-Origin on the server where the script resides.

Access-Control-Allow-Origin: *
Copy the code

Then, set the Crossorigin property in the

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

Crossorigin =”anonymous” in the code above means that no identity information is required to read the file, that is, cookies and HTTP authentication information are not required. If crossorigin is set to “use-credentials”, the browser uploads cookies and HTTP authentication information, and the HTTP header access-Control-allow-credentials need to be enabled on the server.

The event listener property of the Window object

In addition to having the GlobalEventHandlers interface that element nodes have, the Window object also has the following event listener properties.

  • window.onafterprint:afterprintA listener function for the event.
  • window.onbeforeprint:beforeprintA listener function for the event.
  • window.onbeforeunload:beforeunloadA listener function for the event.
  • window.onhashchange:hashchangeA listener function for the event.
  • window.onlanguagechange: languagechangeThe listener function of.
  • window.onmessage:messageA listener function for the event.
  • window.onmessageerror:MessageErrorA listener function for the event.
  • window.onoffline:offlineA listener function for the event.
  • window.ononline:onlineA listener function for the event.
  • window.onpagehide:pagehideA listener function for the event.
  • window.onpageshow:pageshowA listener function for the event.
  • window.onpopstate:popstateA listener function for the event.
  • window.onstorage:storageA listener function for the event.
  • window.onunhandledrejection: of an unprocessed Promise objectrejectA listener function for the event.
  • window.onunload:unloadA listener function for the event.

Multiwindow 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.

Window reference

Scripts within each window can reference other Windows. Browsers provide special variables that return other Windows.

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

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

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

The following code reverses the access history of the parent window once.

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 tag, the

tag, and so on.

  • _top: Top-level window
  • _parent: the parent window
  • _blankNew window:

The following code opens the link in the top-level window.

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

The iframe element

For embedded Windows, the document.getelementById method gets the DOM node of the window and then uses the contentWindow property to get the window object that the iframe node contains.

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

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

// Gets the title of the child window
frameWindow.title
Copy the code

The contentDocument property of the

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

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

The

Inside the

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

The window object of the

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

f1Window.frameElement === f1Element // true
window.frameElement === null // true
Copy the code

The window frames attributes

The window.frames property 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 that window.frames is the value of each member of the window within the frame (that is, the frame’s window object), not the DOM node of the parent window for the iframe tag. To get the DOM tree inside each frame, use window.frames[0].document.

In addition, if the


window.myFrame // [HTMLIFrameElement]
frames.myframe === myFrame // true
Copy the code

In addition, the value of the name attribute automatically becomes the name of the child window, which can be used in the second argument to the window.open method, or in the target attribute of the and tags.