What is BOM?

BOM, which stands for Browser Object Model in Chinese, provides a set of apis for manipulating the browser. Together with ECMAScript and DOM, JavaScript is made up. In the early days of the Web, BOM had no standard specification and was implemented entirely by different browser vendors, so there could be differences between browsers. The BOM specification was added to the HTML5 specification to remedy this problem.

What does a BOM do?

Open a new TAB.

<button id="btn">Open baidu home Page</button>

<script>
  const btn = document.getElementById("btn");
  btn.addEventListener("click".() = > window.open("https://www.baidu.com"));
</script>
Copy the code

Close the current TAB.

<button id="btn">Close the page</button>

<script>
	const btn = document.getElementById('btn')
	btn.addEventListener('click'.() = > window.close())
</script>
Copy the code

A new browser window is displayed.

Move the window. Zoom window. Control user browsing history. Get browser details. Get user display resolution details. More.

What does a BOM contain?

JavaScript was originally created for Web browsers, but it has since evolved into a multipurpose and multiplatform language. Any platform that can provide a JavaScript runtime can be called a JavaScript hosting environment (host).

Currently, the mainstream JavaScript platforms include Web browsers and Node.js that can run the server.

Any platform needs a Global/Root/Host object that extends its own objects and functions in addition to those provided by the ECMAScript language itself.

The global object in the browser environment is window, which extends the DOM and BOM.

In addition to having global objects, Windows also has another meaning, which is “browser window”.

Its composition is as follows:



As you can see from the figure, BOM consists of six objects: Navigator, Screen, Location, Frames, History, and XMLHttpRequest. Here are their uses, one by one.

Navigator

The Navigator object records visitor information. Example code for getting commonly used attributes is as follows:

<div id="info"></div>

<script>
  const info = document.getElementById("info")
  info.innerHTML += 'Browser application name:${navigator.appName} </br>`
  info.innerHTML += 'Browser application code:${navigator.appCodeName} </br>`
  info.innerHTML += 'Browser Engine:${navigator.product} </br>`
  info.innerHTML += 'Browser version:${navigator.appVersion} </br>`
  info.innerHTML += 'Browser proxy:${navigator.userAgent} </br>`
  info.innerHTML += 'Browser platform:${navigator.platform} </br>`
  info.innerHTML += 'Browser language:${navigator.language} </br>`
  info.innerHTML += 'Browser online or not:${navigator.onLine} </br>`
  info.innerHTML += 'Whether to enable cookies:${navigator.cookieEnabled} </br>`
  info.innerHTML += Number of processor cores:${navigator.hardwareConcurrency} </br>`
</script>
Copy the code

attribute

attribute role
appName Name of the browser application
appCodeName Browser application code
product Browser engine
appVersion Browser Version
userAgent Browser proxy
platform Browser platform
language Browser language
onLine Whether the browser is online
cookieEnabled Whether to enable cookies
hardwareConcurrency Processor core number

None of the properties of the Navigator object are guaranteed to return the correct value because:

Different browsers can use the same name to navigate data that can be changed by the browser owner Some browsers misidentify themselves to bypass site tests browsers cannot report new operating systems released later than browsers

But you don’t need to worry too much, because regular users don’t play around with these attributes. Almost all of the properties on Navigator are read-only. Even if you change the value of the property, it doesn’t do anything, and it certainly doesn’t report an error.

navigator.appCodeName = ""
console.log(navigator.appCodeName) // "Mozilla"
Copy the code

In fact, most of the properties on Navigator are designed to be compatible with older programs and are basically meaningless. AppName, for example, has only two values, Netscape and Microsoft Internet Explorer. Only Internet Explorer browsers lower than version 11 return Microsoft Internet Explorer, and all other browsers are Netscape. Two of the more common attributes are userAgent and onLine.

Mobile device models: userAgent

UserAgent can be used to identify different platforms and browsers. However, since the user can modify the string, different types of devices, etc., using this attribute to identify the browser is not a good method, but it can be roughly accurate to identify the mobile device model. Working with userAgent strings yourself requires a lot of regular expressions and is error-prone, a very cumbersome process. Ua-parser-js is recommended. It takes only two lines of code to get the complete user agent information.

var parser = new UAParser();
console.log(parser.getResult());
Copy the code

Listening device onLine or offline status: onLine

Windows provides two events: Online and Offline. You can check whether the device is offline by listening to these two events and using the online attribute.

window.addEventListener('online',  printNetworkState);
window.addEventListener('offline', printNetworkState);

function printNetworkState() {
  console.log(navigator.onLine ? "Your network is back up." : "Your network is down.");
}
Copy the code

To debug Network status, select the Network panel in the browser console and click the WIFI icon.



This brings you to the Network Conditions panel. Click on Network Throttling to select a different Network state.



In addition to the above attributes, there are several new attributes added in HTML5 that are useful for mobile development, such as getBattery, Connection, and Geolocation.

Battery status: getBattery

The API can capture battery status to do things you want to do, such as reduce resource consumption when the battery is low, store data when the battery is about to run out, and prevent data loss. GetBattery returns a BatteryManager object.

attribute

attribute role
charging Boolean value indicating whether the battery is currently charging.
chargingTime Number indicates the remaining time before the battery is charged. The unit is second. If the battery is fully charged, the value is 0.
dischargingTime Number indicates the remaining time before the battery is fully discharged and the system is suspended, in seconds.
level Number indicates the charging level of the battery. The ratio is between 0.0 and 1.0.

The event

The event role
onchargingchange This event is triggered when the battery charging status is updated.
onchargingtimechange This event is triggered when the battery charging time is updated.
ondischargingtimechange This event is triggered when the battery discharge time is updated.
onlevelchange This event is triggered when the battery is updated.

Example:

navigator.getBattery().then(function(battery) {
  function updateAllBatteryInfo(){
    updateChargeInfo();
    updateLevelInfo();
    updateChargingInfo();
    updateDischargingInfo();
  }
  updateAllBatteryInfo();

  battery.addEventListener('chargingchange', updateChargeInfo);
  function updateChargeInfo(){
    console.log(`Battery charging? ${battery.charging ? "Yes" : "No"}`);
  }

  battery.addEventListener('levelchange', updateLevelInfo);
  function updateLevelInfo(){
    console.log(`Battery level: ${battery.level * 100}% `);
  }

  battery.addEventListener('chargingtimechange', updateChargingInfo);
  function updateChargingInfo(){
    console.log(`Battery charging time: ${battery.chargingTime} seconds`);
  }

  battery.addEventListener('dischargingtimechange', updateDischargingInfo);
  function updateDischargingInfo(){
    console.log(`Battery discharging time: ${battery.dischargingTime} seconds`); }});Copy the code

Here are two examples above codepen. Charging Demo 1 Charging Demo 2

Network status: Connection

Connection can obtain the network status of the system to remind users of traffic loss by determining whether the network is cellular or WiFi. You can also offer different quality content by differentiating between 3G/4G/5G. Connection has more fine-grained network state monitoring than the onLoad property. Example:

const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

function printConnectionStatus(e) {
  console.log(e.target);
}

connection.addEventListener('change', printConnectionStatus);
Copy the code

E.target is the current network state object, which contains the following properties.

attribute type role
downlink number Network downlink speed (unit: M/s
effectiveType string Network type: 4G, 3G, or 2G.
onchange null A value indicates that the network status has changed. The default value is NULL
rtt number Round-trip time, in milliseconds, indicates the total time elapsed between the time when the sender sends data and the time when the sender receives an acknowledgement from the receiver. The receiver sends an acknowledgement immediately after receiving data, excluding the data transfer time.
saveData boolean Enable/request data protection mode

Location: geolocation

This API is only available under the HTTPS protocol, and it gets the location. However, the API has a serious position offset, which is prone to inaccurate positioning. Example:

const options = {
  enableHighAccuracy: true.// High accuracy
  timeout: 5 * 1000.// The maximum time to wait for a response in milliseconds
  maximumAge: 0// The maximum length of time the application is willing to accept the cache location
}

if (navigator.geolocation) {
	navigator.geolocation.getCurrentPosition(console.log, console.log, options)
} else {
	console.log('Geolocation is not supported in your browser')}Copy the code

Running this script in any HTTPS web console will bring up an address authorization prompt in the upper left corner.



Click Permit to complete the authorization, and an address icon will appear on the right.



If the browser does not have access to the location itself, you need to authorize it in the operating system Settings, such as on a Mac.



Once authorized, you get a GeolocationPosition object whose COORds property records the current location.

The most important thing is latitude and longitude, like mine:

Latitude, longitude 22.3193039:114.16936109999999Copy the code

Can now be found inAutonavi Open PlatformUse the coordinate picker to query the specific location.

Enter latitude and longitude in the format of longitude plus English comma plus dimension.



Map vendors like Autonavi, Baidu Map and Tencent Map all use this API to complete the H5 SDK.

Camera and microphone: WebRTC

The apis mentioned above are experimental and typically used on mobile. In addition, other functions such as camera/microphone used in WebRTC technology also fall into the category of Navigator. WebRTC is an abbreviation of Web real-time Communication, which is usually used for video chat, voice chat and other scenarios. However, WebRTC content is relatively large, not detailed in this class, the following is a Demo, if you are interested in learning by yourself. WebRTC Demo

Screen

Screen Indicates the screen where the current window is located and provides information about the device. Screen is much simpler than Navigator. It provides the following attributes:

attribute role
height Number, screen height, unit pixel. Usually constant, zooming in and out of the page does not change. But adjusting the screen resolution affects it.
width Screen width, other features same height.
availHeight Number, screen available height, in pixels. The total screen height minus the height of the system’s taskbar or other system components.
availWidth Screen width, other features same as availHeight.
pixelDepth The screen color number, such as 24, represents 24 bits of color.
colorDepth Represents color depth. The difference from pixelDepth is that colorDepth represents the application’s colorDepth, while pixelDepth represents the screen’s colorDepth. Most of the time it’s the same.
orientation Represents screen orientation, is an object.
orientation.angle Number, screen rotation Angle.
orientation.type String, screen direction, landscape-primary horizontal, landscape-secondary reversed horizontal, portrait-primary vertical.

The most common use of Screen is to provide different resources depending on the user’s device. For example, provide two sets of HTML at different resolutions:

if (screen.width > 1920 && screen.height > 1080) {
  location.replace('max.html')}else if (screen.width < 1280 && screen.height < 720) {
  location.replace('min.html')}Copy the code

Location

Records the current URL information and provides a series of operations on the current URL.

attribute

attribute role
href The URL.
protocol The protocol for the current URL, including the colon (:).
host The host. If the port is not the protocol default80and433, will also include a colon (:) and ports.
hostname Host name, excluding port.
port The port number.
pathname The path part of the URL, from the root path/Start.
search Query the string part from the question mark?Start.
hash Fragment string part from#Start.
username The username before the domain name.
password The password before the domain name.
origin The protocol, hostname, and port of the URL.

Of these attributes, only Origin is read-only and the others are writable. As soon as you change the location property, the page changes immediately. If you change the href, the page will immediately jump.

Jump anchor

The most common use is to set the hash so that the page scrolls automatically to the corresponding anchor position. Any element with an ID can be called an anchor. Example (automatic jump to anchor d3 position after 2 seconds) :

<div id="d1">1</div>
<div id="d2">2</div>
<div id="d3">3</div>
<div id="d4">4</div>
<div id="d5">5</div>
<div id="d6">6</div>

<style>
  [id^="d"] {
    height: 400px;
    text-align: center;
    line-height: 400px;
    font-size: 24px;
    font-weight: 600;
    color: #fff;
  }
  #d1 {
    background: #d9e3f0;
  }
  #d2 {
    background: #f47373;
  }
  #d3 {
    background: # 697689;
  }
  #d4 {
    background: #37d67a;
  }
  #d5 {
    background: #2ccce4;
  }
  #d6 {
    background: # 555555;
  }
</style>

<script>
  setTimeout(() = > {
    location.href = "#d3";
  }, 2000);
</script>
Copy the code

methods

Skip page assign

location.assign('http://www.baidu.com')
Copy the code

If the argument is not a valid URL, the page is not redirected, but an exception is thrown.

Replace the current page replace

location.replace('http://www.baidu.com')
Copy the code

The difference between Replace and assign is that replace does not store the previous page browsing history. Instead, replace replaces the old URL with a new ONE, which means the page cannot be reassigned.

Reload the page

location.reload()
Copy the code

Reload is the equivalent of hitting the refresh button in the browser.



Reload can pass a Boolean parameter.

When set to true, resources are forced to be rerequested from the server. If set to false, the browser cache is used. The default is false.

Convert to the string toString

Equivalent to location.href.

URL and URLSearchParams object

A URL can contain the following sections.

  • Href: The full URL.
  • Protocol: indicates the protocol ending with:. Common ones are HTTP and HTTPS.
  • Hostname: domain name, and protocol separated by //, and port separated by:.
  • Port: indicates the port number, which is usually omitted. The default value is 80.
  • Pathname: indicates the path of a resource on the website.
  • Search: queries parameters to? Begin with an ampersand splicing between each other.
  • Hash: anchor point, starting with #.

BOM provides the URL and the URL SearchParams object to help us manipulate urls more easily. Although most of the time we just need to use string urls, there are times when URL objects can be very useful.

Creating a URL object

You need to use the new keyword, which takes two parameters, the first is a URL, or a path, mandatory; The second is the base path, which is optional. For example, baidu URL:

new URL('https://www.baidu.com')
Copy the code

Plus base:

new URL('/s? ie=UTF-8&wd=url'.'https://www.baidu.com')
Copy the code

The URL object can replace the URL string in many cases because it does implicit conversion. Such as:

location.href = new URL('/s? ie=UTF-8&wd=url'.'https://www.baidu.com')
Copy the code

Parsing URL strings

If you have a URL string, you can also parse it by URL.

const urlStr = "https://www.baidu.com/s?ie=UTF-8&wd=url"

const url = new URL(urlStr)
console.log(url.protocol)// https:
console.log(url.host)// "www.baidu.com"
console.log(url.search)/ / "? ie=UTF-8&wd=url"
Copy the code

coding

In urls, many special strings, such as Chinese characters and Spaces, are illegal. The legal symbols are as follows:

  • URL metacharacters: semicolons (;), comma (.), slash (/), question mark (?), colon (:), at (@),&, the (=), plus (+), dollar sign ($), hash number (#)
  • Semantic characters:a-z.A-Z.0-9, conjunction sign (-), underline (_), point (.), exclamation mark (!), wavy line (~), asterisk (*), single quotation mark ('), parentheses ((a))

All characters except these two are illegal. If you want to contain illegal characters in a string, they must be escaped. The rule is to convert each byte to a percentage sign (%) plus two uppercase hexadecimal letters, according to the default encoding of the operating system. A Chinese character is three bytes, so it is converted to six escape characters. RFC3986 specifies which characters should be escaped. Let’s say you type in the address bar:

https://www.baidu.com/s?wd= front endCopy the code

When you copy it, you will find the following format: www.baidu.com/s?wd=%E5%89… The front two words in the URL are escaped as UTF8 bytecode E5 89 8D and E7 AB AF.

Character escape function

In this case, the browser automatically escaped for us, but if we have a string in JS that is not escaped, then we need to escape it ourselves. Let’s say you have a URL string.

const urlStr = "Front end" https://www.baidu.com/s?ws=
Copy the code

You want to jump to the corresponding page.

location.href = urlStr
Copy the code

It will fail because the front two Characters have not been escaped. JavaScript provides encoding/decoding methods for four urls.

encodeURI

The encodeURI method is used to encode the entire URL. It takes a string that represents the entire URL. It escapes anything other than metacharacters and semantic characters.

encodeURI(urlStr)
// "https://www.baidu.com/s?ws=%E5%89%8D%E7%AB%AF"
Copy the code

encodeURIComponent

The encodeURIComponent method is used to transcode components of the URL. All characters except semantic characters are transcoded, that is, metacharacters are also transcoded. Therefore, ** it cannot be used to transcode the entire URL. ** It takes one argument, which is a fragment of the URL.

encodeURIComponent('front end')
// "%E5%89%8D%E7%AB%AF"
Copy the code

If you escape the entire URL, you can’t.

encodeURIComponent(urlStr)
// "https%3A%2F%2Fwww.baidu.com%2Fs%3Fws%3D%E5%89%8D%E7%AB%AF"
Copy the code

In the above code, encodeURIComponent escapes with URL metacharacters, so transcoding the entire URL will cause problems.

decodeURI

The decodeURI method is used to decode the entire URL. It is the inverse of the encodeURI method. It takes one argument, the transcoded URL.

const urlEncode = encodeURI(urlStr)
// "https://www.baidu.com/s?ws=%E5%89%8D%E7%AB%AF"
const urlDecode = decodeURI(urlEncode)
// "https://www.baidu.com/s?ws= front-end"
Copy the code

decodeURIComponent

DecodeURIComponent is used to decode URL fragments. It is the inverse of the encodeURIComponent method. It takes a single parameter, the transcoded URL fragment.

decodeURIComponent('%E5%89%8D%E7%AB%AF')
// "front-end"
Copy the code

URLSearchParams object

The search string is a piece of text that is not very easy to process. Let’s say I have a URL like this:

https://www.baidu.com/s?wd=url&ie=utf-8
Copy the code

Its query parameters section is as follows:

wd=url&ie=utf-8
Copy the code

This query parameter, if we want to replace ie values or wd values we need to use regular matching or similar troublesome techniques. (I did this before I touched URLSearchParams.) It would be most convenient if we could manipulate this text like an object. URLSearchParams provides this approach.

let url = new URL('https://www.baidu.com/s?wd=url&ie=utf-8');
url.searchParams.set('wd'.'searchparams');
console.log(url);
Copy the code

In addition to the set method, URLSearchParams provides many more methods that you can try one by one.

methods role
append Add new query parameters
delete Deleting query Parameters
get Gets a query parameter
getAll Gets all query parameters. Because wd=url&wd=uri is legal, it returns an array.
has Check whether a query parameter exists.
set Modify a query parameter.
sort Sorting parameters is rarely used.

Encode function with URL/URLSearchParams

The difference between the encode function and the URL/URLSearchParams object is that the encode function is based on RFC2396, an outdated URL specification. The URL and URLSearchParams are based on the latest RFC3986. Encode has problems when dealing with IPV6. This is rare, though, and in the vast majority of cases, the encode function works fine.