编程知识 cdmana.com

Quickly understand the BOM model of JavaScript

ECMAScript yes JavaScript At the heart of , and BOM( Browser object model ,Browser Object Model) Is in Web Use in JavaScript At the heart of .

stay BOM In the object ,window Objects are top-level objects , In a browser environment, it's a Global Global object , Other objects are window A child of an object ( attribute ).BOM It is mainly used to manage the browser window and the communication between windows . Here is BOM The structure of objects .

image

window object

window yes BOM Core objects of , Represents an instance of a browser . There are two roles , That is to say JavaScript An interface for accessing browser windows , again ES Stipulated Global object . This means any object defined in the web page 、 Variables and functions , Are subject to window As its Global object .

var age = 29;
function sayAge() {
    console.log(this.age);
}
console.log(window.age);    // 29
sayAge();                    // 29
window.sayAge();            // 29

As shown above , Variables and functions defined in the global scope are automatically assigned to window Object name . and sayAge() In global scope , Methods this.age Mapped to window.age, So it's still showing the right results .

However , Defined global variables cannot be passed through delete Operator delete , It's defined in window Properties on objects can be .

window except locationnavigatorscreenhistory and document Outside , There are also some properties .

  • window.console: return Console References to objects , You can output log information to the browser console . Only for debugging , It should not be presented to users .( read-only )
  • window.frames: Array objects , Lists all direct subwindows of the current window .( read-only )
  • window.frameElement: The current window is embedded in another window ( The embedded <object>、<iframe>), If the current window is the top level , return null.( read-only )
  • window.innerHeight: The view visible height of the window ( Company : Pixels ), It also includes the height of the scroll bar .( read-only )
  • window.innerWidth: The view width of the window ( Company : Pixels ), It also includes the width of the scroll bar .( read-only )
  • window.length: The current window contains the number of frames . The framework is <frame> And <iframe>.( read-only )
  • window.locationbar: Check visibility Property's address bar object , Used to indicate whether or not it is visible .( read-only )
  • window.localStorage: visit Document The object of the source Storage; Store data in browser session . similar sessionStorage, But data can be kept for a long time ; And at the end of the page session ,sessionStorage The data will be cleared .( read-only )
  • window.menubar: Check visibility Properties of the menu bar object , Used to indicate whether or not it is visible .( read-only )
  • window.outerHeight: The height of the entire browser window ( Company : Pixels ).( read-only )
  • window.outerWidth: The width of the entire browser window ( Company : Pixels ).( read-only )
  • window.parent: Reference to the parent window of the current window or child window .( read-only )
  • window.personalbar: Check visibility Properties of the personal toolbar object , Used to indicate whether or not it is visible .( read-only )
  • window.scrollX: Page horizontal scroll distance ( Company : Pixels ),window.pageXOffset Alias .( read-only )
  • window.scrollY: Page vertical direction has scrolled distance ( Company : Pixels ),window.pageYOffset Alias .( read-only )
  • window.scrollbars: Check visibility Property , Used to indicate whether or not it is visible .( read-only )
  • window.self: Point to the present window References to objects .
  • window.sessionStorage: Allow access to... Of the current source sessionStorage object . And localStorage be similar , Difference is that sessionStorage Clear at the end of the page session , and localStorage No expiration time .
  • window.top: Window level top most window reference .
  • window.windowwindow Object itself .

Introduced some window Properties of , Let's take a look at window Methods .

Message box

window There are three types of message boxes : Warning box alert、 Confirmation box confirm And prompt box prompt.

window.alert(message) A warning dialog will be displayed , It shows the specified text content and an OK button . for example window.alert(" Warning box coming "); Is shown below :

image

window.confirm(message) Is a modal box with optional messages . Confirmation box used to verify whether the user action is accepted .

var result = window.confirm(" Do you want to leave? ?");
if (result) {
    //  Press OK to perform the operation 
    console.log(" determine ");
} else {
    //  Press cancel to perform the operation 
    console.log(" Cancel ");
}

Running results :

image

window.prompt(text, value) It is a prompt box for displaying text information and prompting users to input text .

  • text The parameter is the prompt content that prompts the user to input information , Omission .
  • value The parameter is the default value in the text input box , Omission .
var result = window.prompt(" When is your birthday ?", "1997-01-01");
if (result == "2011-10-23") {
    alert(" You're the same birthday as me !");
}

The effect is as follows :

image

Click OK , The text in the text input box is returned . If it is empty , Then return an empty string . Click Cancel , return null.

All three methods have blocking effect , Once the dialog box pops up , The entire page is suspended , Waiting for the user to respond .

window There are also several ways to control the window . for example open()close()stop()moveBy()/moveTo()resizeBy()/resizeTo(). Here's what they do .

The window opens & close

window.open(url, target, features, replace) Method is used to create a new window .

  • url Parameter loaded for the new window URL.
  • target Parameter is the name of the new window . Every window has one window.name, Here you can specify the window to use for pop ups , If it doesn't exist , New window . The name can be used as <a> or <form> Properties of target Value . String cannot contain white space characters . Be careful :target It's not a new window title .
  • features The parameter is a string value , The content is separated by commas , Parameters cannot have spaces , for example width=200,height=100.
var params = 'scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,width=0,height=0,left=-1000,top=-1000';
window.open('/', 'test', params);

features The values that can be set are :

  • left/top: The latest window on the left (left) With the top (top) Distance of ( Company : Pixels ). New window visible , It can't be set off the screen .
  • width/height: The width and height of the new window ( Company : Pixels ). The width and height shall not be less than 100.
  • outerWidth/outerHeight: The width and height of the entire browser window .( Company : Pixels ). The width and height shall not be less than 100.
  • menubar: Show menu bar or not .
  • toolbar: Show toolbar or not .
  • location Show address bar .
  • personalbar: Whether to display the user installed toolbar .
  • status: Is the status bar displayed .
  • resizable: Whether the new window can be resized .
  • scrollbars: Whether the scroll bar appears .
  • titlebar: Show title block or not .
  • close: Is the close button displayed .

The same-origin policy , Only the same content in the same window can be accessed ( Same agreement ://domain:port).

window.close() Method is used to close the current window , It's usually used to close window.open() Method to create a new window . Use window.closed Property to determine whether the window is closed .

Close the window in the current window :

window.close();

window.stop() Method is equivalent to clicking the browser's stop button . Because of the script loading order , This method cannot block documents that are already included in the load , But it can stop pictures 、 New windows and delayed loading of objects .

window.stop();

The window moves

window.moveBy(deltaX, deltaY) Method according to the specified value , Move the current window .

  • deltaX: The pixel value of the window moving horizontally .
  • deltaY: The pixel value of the window moving vertically .

window.moveTo(x, y) Method to move the current window to the specified coordinate position .

  • x: The abscissa of horizontal movement
  • y: The ordinate of the vertical movement

moveBy() What happens is relative movement ,moveTo() What happens is absolute movement .

When , Common web page JavaScript Cannot move browser window by calling this function :

  1. The current window or tab is not created by window.open Method to create ;
  2. The window where the current tab is located contains multiple tabs .

window.resizeBy(xDelta, yDelta) Method is used to adjust the size of the window .

  • xDelta: The pixel value of the window changing horizontally .
  • yDelta: The pixel value of the vertical direction of the window .

window.resizeTo(aWidth, aHeight) Method is used to adjust the size of the window .

  • aWidth: Integers , According to the new outerWidth( Company : Pixels ).
  • aHeight: Integers , According to the new outerHeight( Company : Pixels ).

resizeBy() Relative size method to adjust the window size ,resizeTo() Absolute size method to adjust the window size .

According to the following rules , Common web page JavaScript The browser window cannot be resized by calling this function :

  1. You can't set which is not through window.open Created window or Tab Size ;
  2. When a window contains more than one Tab when , Unable to set window size .

Window scrolling

window.scroll() Scroll the window to a specific location in the document ,
window.scrollBy() Scroll the document by the offset specified in the window ,
window.scrollTo() Scroll the window to a specific location in the document .

The parameters of the above three methods can be x-coord and y-coord Two parameters , perhaps options One parameter .

  • x-coord: Horizontal pixel abscissa .
  • y-coord: Vertical pixel ordinate .

perhaps

  • options: One ScrollToOptions Dictionaries .
//  Move to... On the horizontal axis 100 Pixels to the left of the window , Move to... On the vertical axis 100 Pixels at the top of the window 
window.scroll(100, 100);
//  perhaps 
window.scroll({
    top: 100,
    left: 100,
    behavior: 'smooth'
});

options There are three properties :

  • top: The pixel value of the vertical scroll
  • left: Horizontal scrolling pixel value
  • behavior: Scrolling mode ,smoothinstant and auto, The default value is auto.

It's the same way , But the function is different .window.scrollBy() Scroll the specified distance ,window.scroll() Scroll to the absolute position in the document ,window.scrollTo() Actually and window.scroll() The method is the same .

Print

window.print() Methods open the print dialog box to print the current document .

In a development project , If there is a web page that provides printing service , We can set a button in the page , Call printing function ; But before , We need to determine whether printing is supported .

if (typeof window.print === 'function') {
    //  Support printing function 
        document.getElementById('printLink').onclick = function () {
        window.print();
    }
}

The focus of pop-up window / Defocus

Use window.focus() and window.blur() Method can be window gain or lose focus .

There are other ways , I won't introduce it here .

location

location Object provides information about the document loaded in the current window , There are also some navigation functions . That is window Object properties , It's also document Object properties . It can also be parsed URL. Here is a list of location Properties of .

  • location.href: complete URL value , Allow updates .
  • location.origin: Domain name standard form . Include agreement 、 domain name 、 Port number .
  • location.protocol: At present URL The agreement , Including colons (:).
  • location.host: domain name , contain : Port number after .
  • location.hostname: domain name , Excluding port number .
  • location.port: Port number .
  • location.pathnameURL The part of the middle path , from / Start .
  • location.searchURL Parameters of the part , From question mark ? Start .
  • location.hash: Block identifier section , from # Start .
  • location.usernameURL The user name before the domain name .
  • location.passwordURL Password before domain name .

Only origin Properties are read-only , Other attributes can be written .

Let's give you a URL http://localhost:8088/mall/?page=1&userid=2#part=top, Use the above property to get it .

location.href;        // http://localhost:8088/mall/?page=1&userid=2#part=top
location.origin;    // http://localhost:8088
location.protocol;    // http:
location.host;        // localhost:8080
location.hostname;    // localhost
location.port;        // 8088
location.pathname;    // /mall/
location.search;    // ?page=1&userid=2
location.hash;        // #part=top

However location.search What you get is all the content , There's no way to get each query string parameter one by one . We can create a function to parse and return an object that contains all the parameters .

function getQueryArgs() {
    //  Take the query string and remove the beginning question mark 
    var qa = (location.search.length > 0 ? location.search.substring(1) : ""),
    //  The object that holds the data 
    args = {},
    //  Take each item 
    items = qa.length ? qa.split("&") : [],
    //  Each item and its key value 
    item = null,name = null,value = null,
    len = items.length;
    //  Add each item to... One by one args In the object 
    for (let i = 0; i < len; i++) {
        item = items[i].split("=");
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        if (name.length) {
            args[name] = value;
        }
    }
    return args;
}

Be careful , If the location.href Write a new URL Address , The browser will immediately jump to the new address .

In addition to the above attributes ,location There are several other ways .

assign

location.assign(url) Method reception URL String makes the browser jump immediately . An error will be reported when the parameter is invalid .

location.assign('http://www.sample.com');

And give window.location and location.href Two property assignments and calls assign() The effect of the method is the same .

replace

location.replace() And location.assign() The method is similar to , It's all about jumping to the new URL, But not in history History New records are generated in it , The back button cannot go back to the current page . When the script finds that it is currently a mobile device , have access to replace Jump to mobile page .

//  Jump to a new URL 
location.replace('http://www.sample.com');

reload

location.reload(boolean) Method is used to reload the current page . When the parameter is false Or empty , The browser reloads the page from the local cache and locates it to the current location . Parameter is true when , The browser re requests from the server , And position to the top ( namely scroillTop===0).

location.reload();            //  Reload ( It's possible to load... From the cache )
location.reload(true);        //  Reload ( Reload from server )

stay reload() Later code may not execute , It depends on factors such as network delay or system resources . It is best to reload() On the last line of code .

location.toString() Method returns the whole URL character string , Equivalent to reading location.href attribute .

navigator object

navigator Used to get current browser information . have access to window.navigator Property retrieval navigator object .

  • appCodeName: Browser code name .Mozilla,Netscape 6 and IE5 The internal names of are all Mozilla.( read-only )
  • appName: The name of the browser . Due to compatibility issues ,HTML5 The specification allows this property to return Netscape.( read-only )
  • appVersion: Browser version number . Generally, it does not correspond to the actual version .( read-only )
  • connection: Provide NetworkInformation Object to get the network connection information of the device .( read-only )
  • cookieEnabled: Whether the current page of the browser is enabled cookie.( read-only )
  • geolocation: return Geolocation object , The location information of the device can be accessed . Security considerations will prompt Authorization .( read-only )
  • hardwareConcurrency: The browser environment has CPU The core number .( read-only )
  • keyboard: return Keyboard object , Provides the ability to retrieve the keyboard layout and switch between capturing keys from the physical keyboard .( read-only )
  • language: Browser main language .( read-only )
  • languages: An array of languages used by visitors , In order of priority . The first element is assigned to language, When the value changes ,window Trigger languagechange event .( read-only )
  • mimeTypes: return MimeTypeArray object , Containing recognizable MimeType An array of objects .( read-only )
  • maxTouchPoints: Returns the maximum number of touch points supported by the current device at the same time .( read-only )
  • onLine: Indicates whether the browser is currently connected to the Internet .( read-only )
  • oscpu: Returns the operating system of the client computer or the CPU. stay Firefox You can get this value in .
  • permissions: Returns a query that can be used to query or update certain APIs Object of the permission state of .( read-only )
  • platform: Browser system platform type . Not sure if this value is valid .( read-only )
  • plugins: return PluginArray object , Contains all plug-ins installed by the browser .( read-only )
  • product: Current browser product name . For the purpose of compatibility , return "Gecko" value .( read-only )
  • serviceWorker: return ServiceWorkerContainer object , Provide right ServiceWorker Registration of 、 Delete 、 Upgrade and communication access .( read-only )
  • storage: Return to single example StorageManager object , Persistent storage for maintaining data , Roughly determine the space for storing data .( read-only )
  • userAgent: Returns the user agent of the current browser .( read-only )
  • vendor: Browser vendors . for example Chrome It shows that Google Inc..
  • vendorSub: Secondary information about suppliers .

Let me introduce you navigator Some methods in objects .

javaEnabled

javaEnabled() Indicates whether the browser is enabled Java. Is whether the current configuration file is allowed to use Java, Not whether the browser supports Java.

if (window.navigator.javaEnabled()) {
    //  Browser Java You can use 
}

sendBeacon

sendBeacon(url, data) Is used to pass the HTTP Transfer a small amount of data asynchronously to Web The server . When the transmission is successful true.

  • url For the address sent ;
  • data yes ArrayBufferViewBlobDOMString perhaps FormData Data of type .

The following example shows a theoretical statistical code —— Uninstall the event handler by trying to synchronize XMLHttpRequest Send data to the server . This causes page offloading to be delayed .

window.addEventListener('unload', logData, false);
func logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", flase);    //  The third parameter indicates that it is synchronous xhr
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}

This is it. sendBeacon() The significance of the existence of methods . Use sendBeacon() The method allows users to send data asynchronously to the proxy server , At the same time, it will not delay the unloading of the page or affect the loading performance of the next navigation . This solves all the problems of submitting analytical data : Reliable data , The transmission is asynchronous and does not affect the loading of the next page . Besides , The code is actually much simpler than other technologies !

The following example shows a theoretical statistical code pattern —— By using sendBeacon() Method to send data to the server .

window.addEventListener('unload', logData, false);
function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

registerProtocolHandler

registerProtocolHandler(scheme, url, title) It can make Web The site registers itself with functions that can be used to open or process specific protocols .

  • scheme: String containing the site processing protocol . for example , Pass in "sms" To register for processing SMS Text information link .
  • url: The processor URL character string . It should contain a "%" Place holder , Will be accepted by the document escaped Link replaced . This link may be a real URL, Or a phone number , Email address and so on .
  • title: Processor title . Show it to the user , For example, pop up " Allow sites to process [scheme] Link ?" Or list registered processors in browser settings .
The processor URL Must be http perhaps https Protocol tag start , It is best to https, To meet the security requirements of some browsers .

screen object

screen Object represents the current screen window , Often refers to what is currently being rendered window object , Provide information about the display device . Not very useful . It mainly introduces several properties .

  • availTop: Returns the pixel value of the browser's free space at the top of the screen .
  • availLeft: Returns the pixel value of the browser's available space on the left side of the screen .
  • availWidth: Returns the horizontal width of the browser's available space .
  • availHeight: Returns the vertical height of the browser's available space .
  • colorDepth: Return to the color depth of the screen (color depth). according to CSSOM(CSS The object model ) View , For compatibility , The value is always 24.
  • height: Back to the height of the screen ( Company : Pixels ).
  • orientation: Return to one ScreenOrientation example , Indicates the direction of the current screen .
  • pixelDepth: Returns the bit depth of the screen / Color depth (bit depth). according to CSSOM(CSS The object model ) View , For compatibility , The value is always 24.
  • width: Back to the width of the screen ( Company : Pixels ).

history object

history Object holds the history of the browser . For safety reasons , Developers don't know what the user's browser is URL. But you can go back and forward through the history list . Here is history The main properties of the object .

  • length: Returns... In the current window history list URL Number .
  • scrollRestoration: allow Web The application displays the default scrolling recovery behavior on the history list .
  • statehistory The state value at the top of the stack .
const scrollRestoration = history.scrollRestoration;
if (scrollRestoration) {
    //  Prevent automatic recovery of page position 
    history.scrollRestoration = 'manual';
} else {
    //  View the current page scrolling recovery behavior 
    console.log('The location on the page is not restored, user will need to scroll manually.');
}

You can also use history Provides methods to access history .

go

go() Method can jump in the user's history at will . Pass the number of pages to jump to .

history.go(-1);        //  Back to a page 
history.go(2);        //  Two pages ahead 

You can also pass string parameters that exist in the history , If the history does not contain the passed string , Then do nothing .

history.go("sample.com");

You can also use back() Methods back and use forward() Instead of go() Function of method .

Be careful , When moving to a previously visited page , Pages are usually loaded from the browser cache , Instead of re asking the server to send new pages .

pushState

pushState(state, title, url) Method can add a record to the history without loading the page . This method takes three parameters :

  • state Parameters are state objects , And pushState Associated with the added record . Represents the browser's state attribute .
  • title Parameter is document.title Value , Generally set as null. Most browsers ignore .
  • url Parameter specifies the new history , To change the current situation url. This parameter cannot cross domain , Agreement , domain name , The ports must be the same , If there is a cross domain situation , You will be prompted .
history.pushState({id:1}, null, '?page=1');

replaceState

replaceState(stateObj, title, url) Method is used to modify history Object's current record , It is to replace the current page in the browser's history . Suppose the current page is sample.com/index.html

history.pushState({id:1}, 'title1', '?page=1');    // URL Is shown as http://sample.com/index.html?page=1
history.pushState({id:2}, 'title2', '?page=2');    // URL Is shown as http://sample.com/index.html?page=2
history.replaceState({id:3}, 'title3', '?page=3');    // URL Is shown as http://sample.com/index.html?page=3
history.back();    // URL Is shown as http://sample.com/index.html?page=1
history.back();    // URL Is shown as http://sample.com/index.html
history.go(2);    // URL Is shown as http://sample.com/index.html?page=3

postate event

When adding or changing history , Will trigger popstate event . If the activated history entry is through the history.pushState() Call to create , Or be right history.replaceState() The impact of the call ,popstate The event state Property contains a copy of the state of the historical entry .

Note that calling history.pushState() or history.replaceState() Not trigger popstate event . Only when making browser actions , Will trigger the event , If the user clicks the browser Back button ( Or in JavaScript Call in code history.back() perhaps history.forward() Method ).

summary

BOM In order to window Object based browser object model , It treats the browser as an object , Used to interact with browser windows .window The object is still Global object , Global variables and functions are its properties and methods , And all the native constructors and other functions are in its namespace . But every browser manufacturer has its own BOM Realization , So the compatibility is poor .

More content please pay attention to the public number 「 Sea people's blog 」, reply 「 resources 」 Free learning resources are available !

image

版权声明
本文为[hireny]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224214844009r.html

Scroll to Top