BOM

BOM Introduction & Writing background

Introduction of BOM

BOM: Broswer Object Model Browser Object Model

In JavaScript, the window object is used to perform browser-related operations

Learning BOM is learning the Window object in JavaScript

Writing background

If you’ve read JavaScript you Don’t Know, there’s a formula in the book that says JavaScript = ES + DOM + BOM

ES and DOM are both familiar to us, and in our daily development, we spend most of our time programming using ES + DOM syntax. I use BOM occasionally. The reason why I suddenly want to write this note is that I almost caused a production bug due to my unfamiliarity with this knowledge a few days ago. Fortunately, the test student found it during the online test, otherwise I would have to take the blame.

After such an event, he also recalled some in his mind, this piece of knowledge is just the beginning of the time, the system over again, most of the knowledge are almost forgotten, even sometimes need to use, Baidu keywords are a little laborious. To sum up, it is necessary to re-learn this piece of knowledge, deepen memory at the same time, the formation of their own notes.

Note: this series of articles is a personal review and improvement type note. Simple examples and concepts will not be explained. Key information and important concepts will be noted

Window object

The core object of the BOM is the Window, which represents an instance of the browser.

In browsers, Windows play a dual role: as an interface object for JavaScript to access the browser, and as a Global object in ES

This means that every object, variable, or function in a web page has the Window as its Global object

— JavaScript Advanced Programming

In plain English, all variables, objects, functions, etc. in a web page are ultimately child properties of the Window object

2.1 Global scope

In ECMAScript, the Window object acts like a Global object. That is, all variables declared in the Global scope and functions become properties and methods of the window, which can pass through the window. Property name (or method name) directly called

The following points need to be noted

  • usewindow.attrDeclared variables andvarDeclared variables have a difference, usevarDeclared variable, cannot be useddeleteDelete, usewindow.Declared variables can be deleted
  • In JavaScript, trying to use an undeclared variable throws an error, but passeswindowObject queries for undeclared variables and only returnsundefined

2.2 Navigation and Window Opening

Window.open () can be used either to navigate to a specific URL or to open a new browser window

This function takes four arguments:

  • URL
  • Window target
  • A property string for a new window, for example:'height=400,width=400,top=10,left=10,resizable=yes'
  • Boolean value to replace current page (only valid if no new window is opened)

If window.open() passes a second argument that is the name of an existing window or frame, the URL specified by the first argument is loaded in the target window

// If a topFrame window exists, open the specified URL in the topFrame window, otherwise create a new window and name it topFrame

window.open('htttp://www.maxiaofei.com'.'topFrame') = = ><a href="http://www.maxiaofei.com" target="topFrame"></a>
Copy the code

Window.open () returns a reference to the new window, the window object of the new window

var myWin = window.open('http://www.maxiaofei.com'.'myWin')
Copy the code

Window.close () is used only for Windows opened through window.open()

The newly created window object has a opener property that points to the original window object that opened it

Location object

Note: Window. location and document.location refer to the same object. Location is both a property of the Window object and a property of the Document object

3.1 Properties of the location object

In the url, for example: http://www.baidu.com:8080/web/javascript/test.js#12345?a=10&b=20

The property name example instructions
hash # 12345 The character following # in UTL returns an empty string if none is present
host www.baidu.com:80 Server name and port number
hostname www.baidu.com Domain name, without port number
href www.baidu.com:8080/web/javascr… Full url
pathname web/javascript/test.js The file path under the server
port 8080 Port number of the URL, null if there is no port number
protocol http Protocol used
search ? a=10&b=20 The query string for the URL, usually? The rest

3.2 Custom query string parameter Returns an object

/ / assume that the current URL: 'http://www.maxiaofei.com/Web/test.js?name=mafei&age=24&sex=m'

function getQueryObj(){
    let location = window.location;
    let queryStr = location.search.length > 0 ? location.search.substring(1) : ' ';
    let obj = {},item;
    let queryArr = queryStr.length > 0 ? queryStr.split('&') : []
    
    for(let i=0; i<queryArr.length; i++){ item = queryArr[i].split('=');
        obj[item[0]] = item[1]}return obj
}

getQueryObj()
{/ / ="
    name: 'maxiaofei'.age: 24.sex: 'm'
}
Copy the code

3.3 modify the location

Every changelocationhashFor any property other than that, the page will reload with the new URL

window.location = 'http://www.maxiaofei.com'

location.search = '? name=mafei&age=18'

location.hostname = 'www.baidu.com'

location.pathname = 'web/html/a.html'

location.port = '1234'
Copy the code

Any changes other than the hash value will generate a new record in the browser’s history, which can be navigated to the previous page using the browser’s back button. You can disable this behavior with the replace() method. Pages opened with replace cannot go back to the previous page

// Try the following code in the browser console, the browser will not support rollback
location.replace('http://www.baidu.com')
Copy the code

3.4 Reloading

throughlocation.reload()Method to reload the page

  • location.reload(): reload (possibly from cache)
  • location.reload(true): reload (reload from the server)

4. Navigator object

The Navigator object is mainly used to get the properties of the browser and distinguish the browser type

Navigator object has many properties and compatibility is complex. Click to learn more about navigator properties

5. History object

Since history is a property of the Window object, every browser window, every TAB, and even every frame has its own History object associated with a particular Window object

— JavaScript Advanced Programming

The following three methods and an attribute are commonly used for history

1. history.go()

  • Receives an integer number or string argument: Jumps to the page whose most recent record contains the specified string
history.go('maixaofei.com')		// Search forward or backward for the specified string page
Copy the code
  • When the parameter is an integer, a positive number indicates that the page is forwarded, and a negative number indicates that the page is forwarded
history.go(3)	// Jump forward to three records
history.go(-1)	// Jump backwards to a record
Copy the code

2. history.forward()

  • Jump forward one page

3. history.back()

  • Jump backwards to a page

4. history.length

  • Gets the number of history records, if it is the first page openedhistory.length == 0, you can use this property to determine whether the currently opened web page is the first web page opened by the window

conclusion

This article mainly introduces several common objects in the browser Object Model (BOM), including Navigator, Window, Location, history

  1. windowIt’s both a JavaScript global object and an instance of the BOM, and all of the global methods, properties, properties in the BOM, can pass throughwindow.To invoke the
  2. windowAs examples of BOM, the most common methods are:window.open().window.close()To open and close a browser window, use the close method to open a page
  3. The location object is also one of the more commonly used BOM objects. It is used to manipulate URL-related information. Any property other than the Hash is reloaded and a history is added to the history
  4. locationThere’s another objectreload()Method to manually reload the page, which accepts an optional argument, istrueReload from the server, otherwise the page might be reloaded from the browser cache
  5. Location objectAnd then there’s a special way,location.replace(), which overwrites and reloads the current page without generating a history in History
  6. The Navigator object is mainly used to obtain browser-related information, so you should pay attention to compatibility when using it. Can be used to retrieve the browser (Chrome, safrai, FireFox, Edge, IE) and so on
  7. The history objectIt is used to manipulate the history of the browser URL. You can use parameters to move forward, backward, or to a specified URL. Can be achieved bylengthProperty gets the number of records to determine whether the current page is the first page opened