头图

foreword

Every JavaScript environment has a global object. Any variables created in the global scope are actually properties of this object, and any functions are methods of it. In the browser environment, the global object is the window object, which represents the browser window containing the web page.

In this article, we will cover some important uses of the Window object:

  • Browser Object Model
  • Get browser information
  • Get and use browser history object
  • Create and control browser windows
  • Get screen size and display details

Browser Object Model

The Browser Object Model (BOM for short) is a collection of properties and methods that contain information about the browser and computer screen. For example, we can find out which browser is being used to view a page, although this method is unreliable. We can also find out the screen size it was viewed on, and which pages have been visited before the current page. It can also be used for the rather dubious practice of creating pop-ups if you like to annoy your users.

There is no official standard for the BOM, although many properties and methods are supported by all major browsers, this has become a de facto standard. These properties and methods are provided by the window object, and each browser window, tab, popup, frame and iframe has a window object.

browser environment

Remember that JavaScript can run on different environments. The BOM only makes sense in a browser environment. This means that other environments may not have window objects, although they still have global objects. For example, Node.js has an object called global .

If you don't know the name of the global object, you can use the keyword this in the global scope to refer to the global object. The following code provides a shortcut for assigning a variable global to the global object:

 const global = this;

Dive into global variables

Global variables are variables created without the const , let or var keywords. Global variables can be accessed throughout the program.

Global variables are properties of the global object. In the browser environment, the global object is the window object. This means that any global variable created is a property of the window object, as can be seen from the following example:

 x = 6;  // 创建的全局变量
>> 6
window.x // 同一个变量可以作为window对象的一个属性被访问
>> 6
// window.x === x
>> true

Normally, you should refer to global variables without using window objects. This reduces character typing and makes your code more portable across different environments. An exception is if you need to check if a global variable has already been defined. For example, if x is not defined, the following code will throw a ReferenceError error:

 if (x) {
    // do something
}

However, if the variable is accessed as a property of the window object, the code will still run fine, window.x will directly return false , meaning the code block will not is executed:

 if (window.x) {
    // do something
}

Some functions such as parseInt() and isNaN() are methods of the global object. In the browser environment, they are the methods of the window object. As with variables, it is customary to omit the window object and access them directly.

dialog

In the browser, there are three functions used to generate the dialog: alert() , confirm() and prompt() . None of these are part of the ECMAScript standard, although all major browsers support them as methods of window objects.

Alert Dialog

window.alert() will pause the execution of the program and display a message in a dialog box. The message is given as a parameter to the method, which always returns undefined :

 window.alert('Hello');
>> undefined

Alert Dialog.png

Confirm dialog

window.confirm() method stops the execution of the program and displays a confirmation dialog. Displays the information provided as a parameter and gives the option to confirm or cancel. Returns a boolean ---fb2fcc86ad37d5ab223f211c2b5e7fdf--- if the user clicks OK, and returns a boolean false true if the user clicks cancel:

 window.confirm('Do you wish to continue?');
>> undefined

Confirm dialog.png

Prompt dialog

window.prompt() method will stop the execution of the program and display a dialog box. Shows the information provided as parameters, and an input field that allows the user to enter text. When the user clicks OK, the text is returned as a string. If the user clicks Cancel, it will return null :

 window.prompt('Please enter your name:');

Prompt dialog.png

Use native dialogs sparingly

It's worth emphasizing again that these methods stop the program while it's executing. This means that at the moment the method is called, everything will stop processing until the user clicks OK or Cancel. This can cause problems if the program needs to process other things at the same time, or if the program is waiting for a callback function.

In some cases, this function can be used due to some advantages. For example, the window.confirm() dialog can be used as a final confirmation to check if the user wants to delete the resource. This will prevent the program from proceeding and prevent the deletion of resources until the user decides what to do with it.

It's also worth noting that most browsers allow users to disable arbitrarily recurring dialogs, which means this feature is unreliable.

browser information

window The object has a series of properties and methods that provide information about the user's browser.

Navigator object

window object has a property called navigator which returns a reference to the Navigator object. Navigator object contains information about the browser in use. The userAgent property above will return information about the browser and operating system in use. For example, if I run the code below, it will show that I am using the Safari 10 version on Mac OS:

 window.navigator.userAgent
>>"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8"

Don't rely on this information, though, as users can modify it to pretend to be another browser. It's also hard to make any sense of the returned string, because all browsers pretend to be other browsers to some extent.

For example, each browser will include the string Mozilla 371b730fcab2b0b231d413dbfe71b365--- on its own userAgent attribute, for legacy Netscape compatibility reasons. userAgent has been deprecated from the official standard, but it is still well supported in all major browsers.

URL

window.location is an object that contains information about the current page URL. It contains some properties that provide information about the different fragments of the URL.

The href property returns the full URL as a string:

 window.location.href
>> "<https://www.sitepoint.com/javascript-window-object/>"

This property (and most of the others in this section) are read/write properties, which means they can be changed by assignment. If the assignment is done, the current page will be reloaded with the new property value. For example, enter the following code into the browser's console, and the browser will redirect to the specified page:

 window.location.href = '<https://www.sitepoint.com/>'
>> "<https://www.sitepoint.com/>"

protocol使用的协议( http , https , pop2 , ftp )String. Note the colon at the end of the string:

 window.location.protocol
>> "https:"

host property returns a string describing the domain name and port number of the current URL. If the default port number 80 is used, the port number is usually omitted:

 window.location.host
>> "www.sitepoint.com"

hostname property returns a string describing the domain name of the current URL:

 window.location.hostname
>> "www.sitepoint.com"

port property returns a string describing the port number, or the empty string if the port is not explicitly declared in the URL:

 window.location.port
>> ""

pathname attribute returns the path string after the domain name:

 window.location.pathname
>> "/javascript-window-object/"

search property returns a string starting with "?" followed by query string parameters. If there is no query string parameter, an empty string will be returned:

 window.location.search
>> ""

hash property returns a string starting with "#" followed by the fragment identifier. If there is no fragment identifier, an empty string will be returned:

 window.location.hash
>> ""

origin property returns a string that shows the protocol and domain name of the current page source. This property is read-only, so it cannot be changed:

 window.location.origin
>> "<https://www.sitepoint.com>"

window.location also has the following methods:

  • reload() method can be used to force a reload of the current page. Passing the parameter true will force the browser to reload the page from the server instead of using the cached page.
  • assign() method can be used to load another resource from the URL provided by the parameter. For example:

     window.location.assign('<https://www.sitepoint.com/>')
  • replace() assign() method, except that the current page is not stored in the browser history. So the user cannot use the back button to go back.
  • toString() method returns a string containing the entire URL:

     window.location.toString();
    >> "<https://www.sitepoint.com/javascript/>"

browser history

window.history attribute can be used to access information about any previously visited pages in the current browser session. Avoid confusing it with the new HTML5 History API.

window.history.length attribute shows how many pages have been visited before reaching the current page.

window.history.go() method can be used to jump to the specified page, 0 means jump to the current page:

 window.history.go(1); // 前进一个页面
window.history.go(0); // 重新加载当前页面
window.history.go(-1); // 后退一个页面

There are also window.history.forward() and window.history.back() methods, which can be used to advance or rewind a page, respectively, as if using the browser's forward and back buttons.

control window

You can use the window.open() method to open a new window. The method receives the URL of the page to be opened as the first parameter, the title of the window as the second parameter, and a series of properties as the third parameter. This can also be assigned to a variable so that the window can be referenced in later code:

 const popup = window.open('<https://sitepoint.com>','SitePoint','width=700,height=700,resizable=yes');

A popup window.png

close() method can be used to close a window, assuming you have a window reference:

 popup.close();

You can also use the window.moveTo() method to move the window. This method accepts two parameters, the X-axis and Y-axis coordinates of the screen to which the window is to be moved:

 window.moveTo(0,0); 
// 移动窗口到屏幕的左上角

You can use the window.resizeTo() method to resize the window. This method accepts two parameters to specify the width and height of the adjusted window size:

 window.resizeTo(600,400);

annoying popup

These methods are largely responsible for giving JavaScript a bad reputation, as they are used to create annoying pop-up windows that often contain intrusive ads. Resizing or moving the user window is also a bad idea from a usability standpoint.

Many browsers block pop-ups and in some cases do not allow calling some of these methods. For example, you cannot resize a window if more than one tab is open. You also cannot move or resize a window that was not created with window.open() .

It is wise to use as few of these methods as possible, so think carefully before using them. There will almost always be a better alternative, and a good programmer will struggle to find it.

screen information

window.screen object contains information about the screen displayed by the browser. You can find out the height and width of the screen in pixels using the height and width properties respectively:

 window.screen.height
>> 1024
window.screen.width
>> 1280

availHeight and availWidth can be used to find the height and width of the screen, which does not include any OS menus:

 window.screen.availWidth
>> 1280
window.screen.availHeight
>> 995

colorDepth property can be used to find the color bit depth of the user's display, although there are very few use cases for this other than collecting user statistics:

 window.screen.colorDepth;
>> 24

More suitable for mobile platforms

Screen objects have more uses for mobile devices. It also allows you to do things like turn off the device's screen, detect changes in its orientation or lock it in a specific orientation.

Use with caution

Many of the methods and properties covered in the previous section have been abused in the past for suspicious activities such as user agent sniffing, or detecting screen size to decide whether to display certain elements. These practices have now been replaced by better practices such as media queries and feature detection.

document object

Each window object contains a document object. This object has a series of properties and methods for handling the page that has been loaded into the window. document The object contains some interesting methods.

document.write()

The write() method just writes a string of text to the page. If the page is already loaded, it will completely replace the current document:

 document.write('Hello, world!');

This will replace the entire document with the string Hello, world! . HTML can be included in a string, which will become part of the DOM tree. For example, the following code will create a <h1> label node and a text child:

 document.write('<h1>Hello, world!</h1>');

document.write() method can also be used inside the <script> tag in the document to inject a string into the markup. This doesn't overwrite other HTML on the page. The following example will place the text "Hello, world!" inside the <h1> tag, and the rest of the page will display normally:

 <h1>
    <script>document.write("Hello, world!")</script>
</h1>

The use of document.write() is highly undesirable because it can only be used by mixing JavaScript in HTML documents. There are still some extremely rare legitimate uses, but a good programmer hardly ever needs to use it.

Summarize

That's all for the main content about the window object, thank you for reading. If you have learned something, please like, collect and forward~


chuck
303 声望41 粉丝