Navigator object, Screen object

The window.navigator property points to a Navigator object that contains browser and system information. The script understands the user's environment information through this attribute.

navigator.userAgent property returns the user agent string of the browser, indicating the manufacturer and version information of the browser.

Below is the userAgent of the Chrome browser.

navigator.userAgent;
// "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"

Identifies the browser through the userAgent attribute, not A good way. Because all situations (different browsers, different versions) must be considered, it is very troublesome, and the user can change this string. There is no uniform regulation on the format of this string, and future applicability cannot be guaranteed. Various Internet devices are emerging in endlessly and it is difficult to exhaust. Therefore, it is generally no longer to identify the browser through it, but to use the "function identification" method, that is, to test whether the current browser supports the JavaScript functions to be used one by one.

However, the mobile browser can be roughly and accurately identified by userAgent by testing whether it contains the mobi string.

var ua = navigator.userAgent.toLowerCase();

if (/mobi/i.test(ua)) {
  // mobile browser
} else {
  // non-mobile browser
}

If you want to identify the browsers of all mobile devices, you can test more characteristic strings .

/mobi|android|touch|mini/i.test(ua);

Navigator.plugins property returns an array-like object, the member is a Plugin instance object, which represents the browser Installed plug-ins, such as Flash, ActiveX, etc.

var pluginsLength = navigator.plugins.length;

for (var i = 0; i < pluginsLength; i++) {
  console.log(navigator.plugins[i].name);
  console.log(navigator.plugins[i].filename);
  console.log(navigator.plugins[i].description);
  console.log(navigator.plugins[i].version);
}

The Navigator.platform property returns the user's operating system information, such as MacIntel, Win32, Linux x86_64, etc.

navigator.platform;
// "Linux x86_64"

navigator.onLine property returns a boolean value, indicating whether the user is currently online or offline (the browser is disconnected).

navigator.onLine; // true

Sometimes, the browser can connect to the local area network, but the local area network cannot connect to the external network. At this time, the onLine property of some browsers will return true, so it cannot be assumed that as long as it is true, the user will be able to access the Internet. However, if it is false, it can be concluded that the user must be offline.

When the user becomes online, the event will be triggered, and when the user becomes offline, the event will be triggered. You can specify the callback functions of these two events through window.ononline and window.onoffline.

window.addEventListener("offline", function (e) {
  console.log("offline");
});
window.addEventListener("online", function (e) {
  console.log("online");
});

Navigator.language property returns a string that represents the browser's preferred language. This attribute is read-only.

navigator.language // "en"
``` The

`Navigator.languages` property returns an array representing the languages ​​acceptable to the user. `Navigator.language` is always the first member of this array. The `Accept-Language` field of the HTTP request header information comes from this array.

```javascript
navigator.languages ​​// ["en-US", "en", "zh-CN", "zh", "zh-TW"]

If this property changes, it will be in window The languagechangeevent is triggered on theobject.

Navigator.geolocation property returns a Geolocation object that contains information about the user's geographic location. Note that this API is only available under the HTTPS protocol, otherwise an error will be reported when the following method is called.

The Geolocation object provides the following three methods.

-Geolocation.getCurrentPosition(): get the user's current position -Geolocation.watchPosition(): monitor the user's position change -Geolocation.clearWatch(): Cancel the monitoring function specified by the watchPosition() method.

Note that when these three methods are called, the browser will pop up a dialog box asking the user for authorization.

navigator.cookieEnabled property returns a boolean value, which indicates whether the cookie function of the browser is enabled.

navigator.cookieEnabled; // true

Note that this attribute reflects the general characteristics of the browser, and has nothing to do with whether to store cookies for a specific website. The user can set a certain website not to store cookies. At this time, cookieEnabled returns true.

navigator.javaEnabled() method returns a boolean value, indicating whether the browser can run Java Applet applets.

navigator.javaEnabled(); // false

Navigator.sendBeacon() method is used to send data to the server asynchronously, see the chapter "XMLHttpRequest Object" for details.

Experimental properties of

Navigator The Navigator object has some experimental properties, which are available in some browsers.

navigator.deviceMemory property returns the amount of memory (in GB) of the current computer. This attribute is read-only and is only available in the HTTPS environment.

Its return value is an approximate value, rounded to the nearest power of 2, usually 0.25, 0.5, 1, 2, 4, 8. If the actual memory exceeds 8GB, 8 is also returned.

if (navigator.deviceMemory> 1) {
  await import('./costly-module.js');
}
```In the

above example, only the current memory is greater than 1GB before loading large scripts.

### Navigator.hardwareConcurrency The

`navigator.hardwareConcurrency` property returns the number of logical processors available on the user's computer. This attribute is read-only.

The CPU of a modern computer has multiple physical cores, and each physical core sometimes supports running multiple threads at once. Therefore, a quad-core CPU can provide eight logical processor cores.

```javascript
if (navigator.hardwareConcurrency> 4) {
  await import('./costly-module.js');
}
```In the

above example, the available logical processor is greater than 4 before the large script will be loaded.

This attribute is used to create a Web Worker, and each available logical processor creates a Worker.

```javascript
let workerList = [];

for (let i = 0; i <window.navigator.hardwareConcurrency; i++) {
  let newWorker = {
    worker: new Worker('cpuworker.js'),
    inUse: false
  };
  workerList .push(newWorker);
}
```In the

above example, as many Web Workers are created as there are available logical processors.

### Navigator.connection The

`navigator.connection` property returns an object that contains information about the current network connection.

-downlink: Estimated effective bandwidth (unit: megabits/second, Mbps), rounded to the nearest multiple of 25KB per second.
-downlinkMax: The maximum downlink speed of the current connection (unit: megabits per second, Mbps).
-effectiveType: returns the equivalent type of the connection, possible values ​​are `slow-2g`, `2g`, `3g`, `4g`.
-rtt: The estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds.
-saveData: Whether the user has set the browser's option to reduce data usage (such as not loading images), return `true` or `false`.
-type: The type of media currently connected, possible values ​​are `bluetooth`, `cellular`, `ethernet`, `none`, `wifi`, `wimax`, `other`, `unknown`.

```javascript
if (navigator.connection.effectiveType === '4g') {
  await import('./costly-module.js');
}
```In the

above example, if the network connection is 4G, load the large script.

## Screen object The

Screen object represents the screen where the current window is located and provides information about the display device. The `window.screen` property points to this object.

The object has the following attributes.

-`Screen.height`: The height (in pixels) of the screen where the browser window is located. Unless the resolution of the monitor is adjusted, this value can be regarded as a constant and will not change. The resolution of the monitor has nothing to do with the browser settings. Zooming the web page will not change the resolution.
-`Screen.width`: The width (in pixels) of the screen where the browser window is located.
-`Screen.availHeight`: the available screen height (in pixels) of the browser window. Because some space may not be available, such as the system taskbar or the Dock area at the bottom of the Mac system screen, this property is equal to `height` minus the height of those system components.
-`Screen.availWidth`: The available screen width (in pixels) of the browser window.
-`Screen.pixelDepth`: Integer, which represents the color digits of the screen, for example, `24` means that the screen provides 24-bit color.
-`Screen.colorDepth`: alias of `Screen.pixelDepth`. Strictly speaking, colorDepth represents the color depth of the application, and pixelDepth represents the color depth of the screen. In most cases, they are the same thing.
-`Screen.orientation`: returns an object that represents the orientation of the screen. The `type` attribute of this object is a string representing the specific orientation of the screen, `landscape-primary` for horizontal placement, `landscape-secondary` for reversed horizontal placement, `portrait-primary` for vertical placement, and `portrait- secondary` means upside-down vertical placement.

The following is an example of `Screen.orientation`.

```javascript
window.screen.orientation
// {angle: 0, type: "landscape-primary", onchange: null}

The following example ensures that the screen resolution is greater than 1024 x 768.

if (window.screen.width >= 1024 && window.screen.height >= 768) {
  // The resolution is not less than 1024x768
}

The following is to guide users to different web pages according to the width of the screen Code.

if ((screen.width <= 800) && (screen.height <
  window.location.replace('small.html');
} else {
  window.location.replace('wide.html');
}