What is the Browser Object Model
BOM: The Browser Object Model provides a content-independent Object structure that slides with the Browser window. The main objects of the Browser API are:
- The Window object — at the heart of the BOM, is the interface that JS uses to access the browser, as well as the Global object specified by ES
- Location object: Provides information about the loaded document in the current window and some navigation capabilities. Both window object ownership and Document object property
- Navigation object: Retrieves system information for the browser
- Screen object: Used to represent information about the display outside the browser window
- History object: stores historical Internet access information of users
1. The Window object
Windows objects are the core of the browser object model, the interface and the global object pair role
- Alert (): System warning dialog box that can receive string parameter display
window.alert(message); // Message is the text string to be displayed in the dialog boxSuch as:window.alert(' Hello, what a wonderful world ');Copy the code
- Confirm (): system confirmation dialog box for confirming and canceling events
result = windows.confirm(message);
// Message is an optional string to display in the dialog box
// result is a Boolean value that can be selected or unselected
window.confirm('What are you looking at?');
Copy the code
- Prompt (): Prompt dialog box that displays acknowledgements with the user and provides text fields in addition to cancellation events
res = window.prompt(text, value);
// res is used to hold input values, or is null
// text Is a string used to store input text
// Value is the value in the text input field and can also be ignored
let text = window.prompt(' Nice to meet you ');Copy the code
- Open (): Creates a cross-browser object that can navigate to a specific pair URL or open a new pair browser window.
window.open(the URL to load, the window target, a particular string, whether a new page replaces the current loaded page in the browser history)let strWindowFeatures = ` menubar=yes, location=yes, resizable=yes, scrollbars=yes, status=yes `;
function openRequestedPopup() {
windowObjectReference =
window.open(
"http://www.cnn.com/"."CNN_WindowName",
strWindowFeatures
);
}
openRequestedPopup();
// a new window will be created and jump to cnn.com
Copy the code
- Onerror (): an event handler that will be called when no exceptions are caught and propagated on the call stack, and will output the error message to the browser console
windows.onerror = function(message,source,lineno, colno,error) {... }; Message: error message (string) Source: script URL (string) where an error occurs Lineno: line number (number) where an error occurs colno: column number (number) where an error occursErrorObject (object)/ / example:
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1){
alert('Script Error: See Browser Console for Detail');
} else {
var message = [
'Message: ' + msg,
'URL: ' + url,
'Line: ' + lineNo,
'Column: ' + columnNo,
'Error object: ' + JSON.stringify(error)
].join(The '-');
alert(message);
}
return false;
};
Copy the code
- SetTimeout (): called when a timeout has elapsed. This is how much time has passed before the code or method is executed
Window. The setTimeout () = > {the console. The log (' I performed ')}, 1000 (ms))
- SetInterval (): How often a code or method is executed in an interval call
Window.setinterval (()=>{console.log(' I executed ')}, 1000(ms))
// Use setInterval to perform the countdown
let num = 10;
let interval = setInterval(() = > {
num --;
console.log(num);
if(num === 0) {
clearInterval(interval);
console.log('done'); }},1000);
// Use setTimeout to perform the countdown
let num = 10;
let timeout = setTimeout(() = > {
num --;
console.log(num);
if(num > 0) {
setTimeout(timeout, 1000);
}else {
console.log('done'); }},1000);
setTimeout(timeout, 1000);
Copy the code
Browser window method
// Get the left and top positions of the browser window
let leftPos = (type window.screenLeft === 'number')?window.screenLeft : window.screenX;
let topPos = (type window.screenTop === 'number')?window.screenTop : window.screenY;
window.moveBy(x, y);
// x represents the pixel value of the horizontal movement of the window
// y represents the pixel value that represents the vertical movement of the window
function test() {
moveBy(10, -10);
}
window.moveTo(x,y);
// x is the x-coordinate of the position moved to
// y is the vertical coordinate of the position moved to
function test() {
// Move the window to the upper-left corner
moveTo(10, -10);
}
Copy the code
Browser window size method
// Get the width and height of the viewport
let inFrameWith = window.innerWith();
let inFrameHight = window.innerHeight();
// Get the height and width of the entire browser window
let inWindowWith = window.outerHeight();
let inWindowHeight = window.outerWith();
// Change the window size (x,y)
// x is the horizontal change of the window pixel value
// y is the pixel value of the vertical change of the window
window.resizeBy(-200.200);
// Dynamically resize the window
// x is an integer, indicating the new outerWith(); (Including scrollbars and window borders)
// is an integer representing the new outerHeight(); (Including scrollbars and window borders)
window.resizeTo(x,y);
function queater() {
window.resizeTo(
window.screen.x / 2;
window.screen.y / 2;
);
}
Copy the code
2. Location object
- Provides information about loading documents in the current window and some navigation functions, is the window object property, also has the document object property
Loaction Main properties of the object;
//location.hash
<a id="test" href="/en/docs/location.href#hello">hello</a>
/ / js parts
let test = document.getElementById('test');
console.log(test.hash); / / return the hello
// location.host
let test = documentThe createElement method (" test "); Test. The href = "HTTP:/ / developer.mozilla.org: 443 / location. The host ";Test. The host = "developer.mozlla.org:443'// host does not contain a port number because 443 is the default port number for the HTTPS protocol
//location.hostname
<a id="test" href="http://developer.mozilla.org/location.hostname">hello</a>
let test = documentThe createElement method (" test ");let result = test.hostname; // The result is developer.mozilla.org
// location.href
<a id="test" href="http://developer.mozilla.org/href">hello</a>
let test = documentThe createElement method (" test ");let result = test.hostname; / / results for http://developer.mozilla.org/href
// location.pathname
<a id="test" href="/en/docs/location.pathname">hello</a>
let test = documentThe createElement method (" test ");let result = test.hostname; / / results for/en/docs/location. The pathname
// location.port
<a id="test" href="http://developer.mozilla.org:443/href">hello</a>
let test = documentThe createElement method (" test "); Test. The href = 'HTTPS:/ / developer.mozilla.org: 443 / location. The port ";
let result = test.prot; // 443 is the default port number for HTTPSL
// location.protocol
<a id="test" href="https://developer.mozilla.org/href">hello</a>
let test = documentThe createElement method (" test ");let result = test.protocol; // Result is HTTPS
// location.search
<a id="test" href="https://developer.mozilla.org/href?q=123">hello</a>
let test = documentThe createElement method (" test ");let result = test.search; // The result is? q=123
let params = new URLSearchParams('result');
let q = parseInt(params.get(q)); // The result is 123
Copy the code
- Location Application scenario
1. Parse the parameters of the URL query string and return an object;
- The search attribute of location is used to obtain the parameters passed in the current URL. If the string containing question mark is found in the URL, it is truncated, and then the string inside is traversed and equal sign is used as a breakpoint. DecodeURIComponent () method is used to parse the specific parameter value, and put it in the object Return from the container of;
2. Open a new page. Or refresh page usage, which consists of three methods
- Assign: location.assign(‘ www.baidu.com ‘) immediately opens a new URL and generates a new record in the browser’s history.
- Replace: location.replace(‘ www.baidu.com ‘) takes only one URL parameter. By jumping to the URL interface, no history is generated in the browser, but the current page is replaced
- reload: Location.reload () reloads the currently displayed page. When no argument is passed, the page is reloaded from the browser if it hasn’t changed since the last request. If true is passed, it forces a reload from the server, the equivalent of CTRL +F5 for Windows
3. The history object
- The history object holds a history of the user’s Internet access from the moment the window was opened. The history object is represented by the window’s browsing history in the form of documents and a list of document states.
window.history.back(); // Equivalent to clicking the browser's back button
window.history.go(-1); // equivalent to history.back();
// window.history.forward(); Stands for one page forward
<button id='test'>hello,word</button>
window.onload = function(e) {
document.getElementById('test').addEventListener('click'.e= > {
window.history.forward(); })}let framesCount = window.length; FramesCount is the number of frames in the window
Copy the code
Ii. Browser event model
1. Event subscriptions
The interaction of the browser is realized through the built-in event response of the browser. Common browser events include document load, element click, etc. Subscribing to browser events can be realized in the following ways.
- Event handle to an HTML property, such as onclick
- Event handle to the DOM property, adding the onclick method to the DOM in js
- Event handle registration: IE8+ (Window methods addEventListener and removeEventListener) and IE8 and below (attachEvent and detachEvent)
2. Event dissemination
Event propagation can be divided into three stages: capture stage, target stage and bubble stage
/ / HTML
<div id="parent" class="flex-center">
parent
<p id="child" class="flex-center">
child
<span id='son' class="flex-center">
son
</span>
</p>
</div>
Copy the code
/ / CSS
#parent {
background-color: bisque;
width: 700px;
height: 700px;
}
#child {
background-color: chocolate;
width: 500px;
height: 500px;
}
#son {
background-color: crimson;
width: 300px;
height: 300px;
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
}
Copy the code
/ / js parts
const parent = document.getElementById("parent");
const child = document.getElementById("child");
const son = document.getElementById("son");
window.addEventListener("click".function (e) {
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("Window capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
parent.addEventListener("click".function (e) {
// e.stopPropagation();
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("The parent trap", e.target.nodeName, e.currentTarget.nodeName);
}, true);
child.addEventListener("click".function (e) {
console.log("The child capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
son.addEventListener("click".function (e) {
console.log("Son capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
window.addEventListener("click".function (e) {
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("The window" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
parent.addEventListener("click".function (e) {
console.log("Parent" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
child.addEventListener("click".function (e) {
console.log("The child bubbling", e.target.nodeName, e.currentTarget.nodeName);
}, false);
son.addEventListener("click".function (e) {
console.log("Son" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
Copy the code
Take a look at the demo below:
Conclusion:
- Capture stage: First window will capture events, then Document, documentElement and body will capture events, and then DOM elements in body will capture events layer by layer, including div and child.
- Target phase: The event for the element son that was actually clicked happened twice, because in the JavaScript code above son bound the event both in the capture phase and in the bubble phase, so it happened twice. It is important to note, however, that the events bound in the capture phase do not necessarily occur first in the target phase; rather, the events bound first occur
- Bubbling phase: The reverse of the capture phase bubbles the event to the window step by step
3. Prevent the event from spreading
- E.toppropagation (): When talking about events, we often hear about preventing bubbling. In fact, this method can not only prevent bubbling of events, but also prevent propagation in the event capture phase
Change the js code above:
const parent = document.getElementById("parent");
const child = document.getElementById("child");
const son = document.getElementById("son");
const flag = ture;
window.addEventListener("click".function (e) {
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("Window capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
parent.addEventListener("click".function (e) {
if (flag) {
e.stopPropagation();
window.alert('You can't light me');
return;
}
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("The parent trap", e.target.nodeName, e.currentTarget.nodeName);
}, true);
child.addEventListener("click".function (e) {
console.log("The child capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
son.addEventListener("click".function (e) {
console.log("Son capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
window.addEventListener("click".function (e) {
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("The window" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
parent.addEventListener("click".function (e) {
console.log("Parent" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
child.addEventListener("click".function (e) {
console.log("The child bubbling", e.target.nodeName, e.currentTarget.nodeName);
}, false);
son.addEventListener("click".function (e) {
console.log("Son" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
Copy the code
Take a look at the page effect:
4. Prevent event default behavior
- E.preventdefault (): Prevents the default behavior of the event from happening, such as clicking on the A TAB to jump to another page, dragging an image to the browser to open automatically, clicking on the submit button of the form to submit the form, etc., because sometimes we don’t want these things to happen, so we need to prevent the default behavior
Then change the code above:
/ / HTML
<div id="parent" class="flex-center">
parent
<p id="child" class="flex-center">
child
<span id='son' class="flex-center">
son
<a href="https://www.baidu.com" id="a-baidu"</a> </span> </p> </div>Copy the code
/ / js parts
const parent = document.getElementById("parent");
const child = document.getElementById("child");
const son = document.getElementById("son");
const baidu = document.getElementById("a-baidu");
baidu.addEventListener('click'.function (e) {
e.preventDefault();
})
window.addEventListener("click".function (e) {
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("Window capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
parent.addEventListener("click".function (e) {
// e.stopPropagation();
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("The parent trap", e.target.nodeName, e.currentTarget.nodeName);
}, true);
child.addEventListener("click".function (e) {
console.log("The child capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
son.addEventListener("click".function (e) {
console.log("Son capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
window.addEventListener("click".function (e) {
// e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
console.log("The window" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
parent.addEventListener("click".function (e) {
console.log("Parent" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
child.addEventListener("click".function (e) {
console.log("The child bubbling", e.target.nodeName, e.currentTarget.nodeName);
}, false);
son.addEventListener("click".function (e) {
console.log("Son" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);
Copy the code
Take a look at the code:
5. Compatibility, encapsulating a binding event function that is compatible with multiple browsers
class conmonEvent {
construtor(e) {
this.element = e;
}
addEvent(type, handler) {
if(this.element.addEventListener) {
this.element.addEventListener(type, handler, false);
} else if (this.element.attachEvent) {
this.element.attachEvent('on' +type, function () {
handler.call(element);
});
} else {
this.element['on'+ type] = handler; }}removeEvent(type, handler) {
if(this.element.removeEventListener) {
this.element.removeEventListener(type, handler, false);
} else if (this.element.detachEvent) {
this.element.attachEvent('on' +type, function () {
handler.call(element);
});
} else {
this.element['on'+ type] = null; }}}// Prevent events (mainly event bubbling, since IE does not support event capture)
function stopPropagation(ev) {
if (ev.stopPropagation) {
ev.stopPropagation(); / / the w3c standards
} else {
ev.cancelBubble = true; // IE}}// Cancel the default behavior of the event
function preventDefault(event) {
if (event.preventDefault) {
event.preventDefault(); / / the w3c standards
} else {
event.returnValue = false; // IE}}Copy the code
3. Browser requests related content
1.XMLHTTPRequest
- The XMLHttpRequest object provides full access to the HTTP protocol, including the ability to make POST and HEAD requests as well as plain GET requests. XMLHttpRequest can return the response from the Web server synchronously or asynchronously, and can return the content as text or as a DOM document.
let xhr = new XMLHttpRequest();
xhr.open('GET'.'http://domain/service');
// request state change event
xhr.onreadystatechange = function () {
// request completed?
if(xhr.readyState ! = =4) return;
if (xhr.status === 200) {
// request successful - show response
console.log(xhr.responseText);
} else {
// request error
console.log('HTTP error', xhr.status, xhr.statusText); }}; xhr.timeout =3000; // 3 seconds
xhr.ontimeout = () = > console.log('timeout', xhr.responseURL);
The progress event can report long-running file uploads
xhr.upload.onprogress = p= > {
console.log(Math.round((p.loaded / p.total) * 100) + The '%');
}
// start request
xhr.send();
Copy the code
2.fetch
- Fetch is an HTTP data request that is an alternative to XMLHttpRequest. Fetch is not a further encapsulation of Ajax, but native JS. The Fetch function is native JS and does not use an XMLHttpRequest object.
1. The cookie is not configured by default
Fetch (' HTTPS:{/ / domain/service ',
method:'GET'.credentials: 'same-oringin'
})
Copy the code
2. Don’t reject mistakes
// HTTP errors such as 404 500 do not cause the fetch to return with porMISE marked reject, and the catch is not triggered
// To accurately determine whether fetch is successful, we need to include the promise resolveed case and determine whether response.ok is trueFetch (' HTTPS:{/ / domain/service ',
method:'GET',
}).then((response) = > {
/ / 404 500
if (response.ok) {
return response.json();
}else {
throw new Error('fetch error');
}
}).then(json= > {
console.log(json);
}).catch(error= > {
console.log('error');
});
})
Copy the code
3. Timeout cannot be set
function fetchTimeout(url, init, timeout = 3000) {
return new Promise((resolve, reject) = > {
fetch(url, init)
.then(resolve)
.catch(reject);
setTimeout(reject, timeout); })}Copy the code
4. End the fetch
const controller = new AbortController();
fetch(
'http://domain/service', {
method: 'GET'.signal: controller.signal
})
.then(response= > response.json())
.then(json= > console.log(json))
.catch(error= > console.error('Error:', error));
controller.abort();
Copy the code
5. Wrap an Ajax request
type AjaxType = 'GET' || 'POST' || 'PUT' || 'DELETE';
interface setOption {
url: string; type? : AjaxType; data: any; timeout? : number }function formatUrl(json) {
let dataArr = [];
json.t = Math.random();
for (let key in json) {
dataArr.push(`${key}=The ${encodeURIComponent(json[key])}`)}return dataArr.join('&');
}
export function ajax(options: IOptions) {
return new Promise((resolve, reject) = > {
if(! options.url)return;
options.type = options.type || 'GET';
options.data = options.data || {};
options.timeout = options.timeout || 10000;
let dataToUrlstr = formatUrl(options.data);
let timer;
/ / 1. To create
let xhr;
if ((window as any).XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
if (options.type.toUpperCase() === 'GET') {
/ / 2. The connection
xhr.open('get'.`${options.url}?${dataToUrlstr}`.true);
/ / 3. Send
xhr.send();
} else if (options.type.toUpperCase() === 'POST') {
/ / 2. The connection
xhr.open('post', options.url, true);
xhr.setRequestHeader('ContentType'.'application/x-www-form-urlencoded');
/ / 3. Send
xhr.send(options.data);
}
/ / 4. Receive
xhr.onreadystatechange = () = > {
if (xhr.readyState === 4) {
clearTimeout(timer);
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
resolve(xhr.responseText);
} else{ reject(xhr.status); }}}if (options.timeout) {
timer = setTimeout(() = > {
xhr.abort();
reject('timeout');
}, options.timeout)
}
xhr.timeout = options.timeout;
xhr.ontimeout = () = > {
reject('timeout'); }}); }Copy the code
Refer to the article
Built-in browser objects/events
26,000 words JS dry goods to share, take you to appreciate the front-end charm!
Browser event system