BOM five objects

Posted by jerk on Sun, 19 Dec 2021 15:21:59 +0100

01-BOM browser object model

1.1-introduction to BOM and DOM

  • The JavaScript language consists of three parts

    • ECMA javascript: defines the syntax specification of js

  • DOM: document object model document object model: everything in an HTML document is a DOM object

    • Dom defines a set of API s for operating HTML documents (addition, deletion, modification and query of nodes)

  • Bom: Browser Object Model browser object model for example, a browser window is a window object

    • Bom defines a set of API s for operating browser windows

  • Bom is mainly composed of five objects:

    • window: browser core object

    • location: contains the URL information of the current page

    • History: the history object is mainly used to record the history of your current window

    • navigator: contains information about the current browser, such as what browser to use, operating system version, etc

    • Screen: get the screen resolution of the user's computer

      • This is generally not used because it has little effect on developers

1.2-window object

  • 1.window object: refers to the current browser window, which is the top-level object in JS

    • (1). All global variables are attributes of the window object: the top-level object

      • document object

      • bom object

      • Global method: alert(),setInterval()

    • (2). As long as it is the attribute and method of window, you can omit window when using it

      • For example: window Alert() can omit the window and write it as alert()

      • For example: window Document can be written as document by omitting window

    • (3). The window object has a special attribute called name

      • It is always a string, no matter what value is assigned to it

  • 2. There are two common methods for window objects: open() and close()

    • open(): opens a window

    • close(): closes a window

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Title</title>
      </head>
      <body>
      
      <input type="button" value="Click me to open a new window" id="open">
      <input type="button" value="I have a surprise" id="close">
      
      </body>
      
      <script>
          /*1.window Object: refers to the current browser window, which is the top-level object in JS
              * (1).All global variables are attributes of the window object: the top-level object
                  * document object
                  * bom object
                  * Global method: alert(),setInterval()
               * (2).As long as it is the attribute and method of window, you can omit window when using it
                  * For example: window Alert() can omit the window and write it as alert()
                  * For example: window Document can be written as document by omitting window
               * (3).window Object has a special attribute called name
                  * It is always a string, no matter what value is assigned to it
                  *
             2.window Object has two common methods: open() and close()
                  * open():Open a window
                  * close():Close a window
      
           */
      
          //1.window is a top-level object, and all global variables are attributes of window objects
          let age = 18;
          console.log ( window.age );
      
          //2. Window can be omitted as long as it is the attribute and method of window object
          console.log ( window.document === document );true
      
          //3.window has a special attribute called name, which is always a string
          console.log ( window.name );//The default is an empty string
          window.name = 123456;
          console.log ( name );//Always a string
          //Even if you redeclare a variable called name, you can't override it
          let name = [123];
          console.log ( name );
      
          //Open a new window
          document.getElementById('open').onclick = function (  ) {
              /**
              * @param The first parameter: URL the URL of the window to be opened
               * @param The second parameter: similar to the target attribute of a tag, whether to replace the current window or open a new window
               * @param The third parameter: new window features: size and position, etc. (new window is valid _blank)
               * @param The fourth parameter: Boolean type true/false: Add / not add the newly opened window to the browser history
               * @return Newly opened window object
              */
             let newWindow = window.open('https://www.baidu.com', '_blank', 'top=100,left=100,width=500,height=300', true );
          }
      
          //close window
          document.getElementById('close').onclick = function (  ) {
              //The parameter is the window object you want to close. If you don't write it, the default is to close yourself
              //1. If the top-level windows are closed, Google and Firefox will fail. If they fail, you can use the following writing method
              //window.close( );
      
              /*2.For security reasons, Google Firefox will intercept our code. js code can only close the interface opened with js code,
              So we use js to pretend to open ourselves in the current window, and then close ourselves*/
              //The url here is not an empty string '', but a blank string ''
              window.open(" ","_self").close();
          }
      </script>
      </html>

      Three events of 1.3-window object

      There are three events in the window object, which records the three processes of the browser window from opening to closing

    • 1.window.onload: this event is triggered only after all contents on the interface are loaded

    • 2.window.onbeforeunload: this event will be triggered before the interface is closed

    • 3.window.onunload: this event will be triggered at the moment when the interface is closed

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Title</title>
      </head>
      
      <script>
          /*window Object has three events that record the three processes of browser window from opening to closing
      
          1.window.onload:This event is triggered only after all contents on the interface are loaded
      
          2.window.onbeforeunload:This event will be triggered before the interface is closed
      
              3.window.onunload:This event will be triggered at the moment when the interface is closed
      
           */
      
          //Since the script tag is written on the body tag, this line of code will be executed before the body content is loaded
          console.log ( document.getElementById ( "p1" ) );//null the compiler has not resolved the p tag at this time
      
          //1.window.onload: triggered after all contents on the interface are loaded
          window.onload = function ( ) {
      
              // Because the compiler parses html files from top to bottom, if our js code is written in front of the body, we may not be able to obtain dom objects
              console.log ( "All current interfaces are loaded" );
              //window.onload will not be executed until the entire interface is loaded no matter where it is written in the interface
              console.log ( document.getElementById ( "p1" ) );
          }
      
          //2.window.onbeforeunload: the interface is triggered before closing
          window.onbeforeunload = function (  ) {
              /*  1.This method is mainly used to save some important data before the interface is closed
              *  2.You can also pop up a prompt box to retain the user
              * */
      
              //return content: the browser will automatically pop up a retention window
              //Google and Firefox will block this disgusting thing, and only IE supports it
              return 'Do you really want to abandon me';
          }
      
          //3 window.onunload: triggered when the interface is closed
          window.onunload = function (  ) {
      
              console.log('The interface is closing');
      
          }
      </script>
      
      <body>
      
      <p id="p1">I am p label</p>
      </body>
      
      
      </html>

      1.4-location object

    • 1.location object: contains the URL information of the current page

      • location.href: global uniform resource locator

      • location.href = protocol name (http) + ip address (domain name) + port number + resource path

      • For the time being, you only need to know that the location object contains the network url information of a web page. The specific meaning will be explained in detail when learning the network in a later stage

    • 2. There are three common methods for location objects

      • (1) Open a new web page: location.assign('url of the new web page you want to open ')

      • (2) Replace the current web page: location.replace('url of the web page to replace ')

      • (3) Refresh the current web page: location reload()

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
        
        <input type="button" id="assign" value="assign Open a new page">
        <br>
        <input type="button" id="replace" value="replace Replace current page">
        <br>
        <input type="button" id="reload" value="reload Refresh current page">
        <br>
        
        </body>
        
        <script>
            /*1.location Object: contains the URL information of the current page
                * url: Global uniform resource locator
                * url = Protocol name (http) + ip address (domain name) + port number + resource path
                * For the time being, you only need to know that the location object contains the network url information of a web page. The specific meaning will be explained in detail when learning the network in a later stage
        
              2.location Object has three common methods
                    * (1)Open a new web page: location Assign ('url of the new web page you want to open ')
                    * (2)Replace current page: location Replace ('url of web page to replace ')
                    *   (3)  Refresh the current web page: location reload()
             */
        
            //1. View location object information
            console.log ( window.location );//location object
            console.log(location.hash);//Resource locator (anchor location)
            console.log(location.host);//Host host = hostname + port
            console.log(location.hostname);//Host name (ip address)
            console.log(location.port);//Port number
            console.log(location.href);//Full url path
            console.log(location.pathname);//Resource path
            console.log(location.protocol);//url protocol
            console.log(location.search);//url requested parameters
        
            //2.assign: open a new web page
            document.getElementById('assign').onclick = function (  ) {
                //History will be left (you can go back)
                window.location.assign('http://www.itheima.com');
                //The above line of code is equivalent to the following line of code
                //window.location.href = 'http://www.itheima.com';
            }
        
            //3.replace: replace the current web page
            document.getElementById('replace').onclick = function (  ) {
                //No history will be left (cannot be rolled back)
                window.location.replace('http://www.itcast.com');
            }
        
            //4. Refresh the current web page
            document.getElementById('reload').onclick = function (  ) {
                //It is equivalent to pressing F5 to refresh the current web page
                window.location.reload();
            }
        
        </script>
        </html>

        1.5-history object

        The history object is mainly used to record the history of your current window

      • The main function is to forward and backward the web page (equivalent to the forward and backward button function in the upper left corner of the browser)

      • history.forward(): forward

      • history.back(): back

      • Jump to the specified number of pages: history Go (number): positive number: how many pages forward, 1: how many pages forward, negative number: how many pages back - 1: return to the previous page
      • <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
        <a href="09-history test page.html">Click me to jump</a>
        <input type="button" value="forward" id="forword">
        </body>
        
        <script>
            /*history Object is mainly used to record the history of your current window
                * The main function is to forward and backward the web page (equivalent to the forward and backward button function in the upper left corner of the browser)
                * history.forward():forward
                * history.back():back off
             */
        
            document.getElementById('forword').onclick = function (  ) {
                //Jump to the next page of the current web page history. If there is no history of the next page, do not jump
                history.forward();
            }
        </script>
        </html>

        1.6-navigator object

        navigator object: contains information about the current browser

      • Application scenario at work: user information statistics (Statistics of user group distribution of my website platform, what browser, what version of windows, etc.)

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
        
        </body>
        
        <script>
            /*navigator Object: contains information about the current browser
                Application scenario at work: user information statistics (Statistics of user group distribution of my website platform, what browser, what version of windows, etc.)
        
             */
        
            console.log ( navigator );//navigator object
            console.log ( navigator.appVersion );//Current browser version information
            console.log ( navigator.platform );//Current browser hardware platform
            console.log ( navigator.userAgent );//Current browser information
        
            //Usage scenario 1: judge whether the current user's operating system is 32-bit or 64 bit
            //Google and IE 64 bit display WOW64 Firefox display Win64
            if(navigator.userAgent.indexOf('WOW64') != -1 || navigator.userAgent.indexOf('Win64') != -1){
                console.log ( "64 position" );
            }else{
                console.log ( "32 position" );
            }
        
            //Usage scenario 2: judge which browser the user is currently using
            if(navigator.userAgent.indexOf('Chrome') != -1){
                console.log ( "Google browser" );
            }else if(navigator.userAgent.indexOf('Firefox') != -1){
                console.log ( "Firefox browser" );
            }else{
                console.log ( "IE browser" );//It may also be other niche browsers, which can be ignored
            }
        
        </script>
        </html>

        ==02 localstorage and sessionstorage==

      • localStorage: local storage
        • Store data in browser
      • grammar
        • Storage: localstorage Setitem ('property name ', property value)
        • Take: localstorage Getitem ('property name ') has a return value

          Delete: localstorage Removeitem ('property name ')

          Empty: localstorage clear()

          3. Precautions

          a. Stored data can only be string type. For other data types, the toString() method is automatically called to convert to a string

          b. Permanent storage. Unless you delete it yourself, it will always exist in the browser

          <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <meta http-equiv="X-UA-Compatible" content="ie=edge">
              <title>Document</title>
          </head>
          <body>
              <button id="btn1">Storage data</button>
              <button id="btn2">Take and store data</button>
              <button id="btn3">Delete stored data</button>
              <button id="btn4">Empty data</button>
          
              <script>
                  /* 
                      1.localStorage:Local storage
                          Store data in browser
          
                      2.grammar
                          Storage: localstorage Setitem ('property name ',' property value ')
                          Take: localstorage Getitem ('property name ')
                          Delete: localstorage Removeitem ('property name ')
                          Empty: localstorage clear()
          
                      3.Attention
                          a.Stored data can only be string type. For other data types, the toString() method is automatically called to convert to a string
                          b.Permanent storage. Unless you delete it yourself, it will always exist in the browser
                   */
          
          
                  //Save
                  document.getElementById('btn1').onclick = function(){
                      localStorage.setItem('name','monitor');
                      localStorage.setItem('age',18);
                      localStorage.setItem('girlFriend',['Aoi Sora','Mr. Bodo','Miss Jize']);
                  }
          
                  //take
                  document.getElementById('btn2').onclick = function(){
                      let age = localStorage.getItem('age');
                      console.log(age); 
                  }
          
                  //Delete
                  document.getElementById('btn3').onclick = function(){
                      localStorage.removeItem('girlFriend'); 
                  }
          
                  //Empty: delete all data at once
                  document.getElementById('btn4').onclick = function(){
                      localStorage.clear(); 
                  }
              </script>
          </body>
          </html>

          1.2-sessionStorage

          1.sessionStorage is equivalent to the short-lived version of localStorage, and other uses are exactly the same

          2. Difference between the two: HP value is different

          localStorage: permanent storage (hard disk exists, HP value is unlimited)

          sessionStorage: temporary storage (memory exists, HP is worth a life, and it will disappear as long as the browser is closed)

          <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <meta http-equiv="X-UA-Compatible" content="ie=edge">
              <title>Document</title>
          </head>
          <body>
              <button id="btn1">Storage data</button>
              <button id="btn2">Take and store data</button>
              <button id="btn3">Delete stored data</button>
              <button id="btn4">Empty data</button>
          
              <script>
                  /* 
                      1.sessionStorage It is equivalent to the short-lived version of localStorage, and other uses are exactly the same
          
                      2.Difference: HP value is different
                          localStorage: Permanent storage (with hard disk, HP value unlimited)
                          sessionStorage: Temporary storage (memory exists, HP is worth a life, and it will disappear as long as the browser is closed)
          
                   */
          
          
                  //Save
                  document.getElementById('btn1').onclick = function(){
                      sessionStorage.setItem('name','monitor');
                      sessionStorage.setItem('age',18);
                      sessionStorage.setItem('girlFriend',['Aoi Sora','Mr. Bodo','Miss Jize']);
                  }
          
                  //take
                  document.getElementById('btn2').onclick = function(){
                      let age = sessionStorage.getItem('age');
                      console.log(age); 
                  }
          
                  //Delete
                  document.getElementById('btn3').onclick = function(){
                      sessionStorage.removeItem('girlFriend'); 
                  }
          
                  //Empty: delete all data at once
                  document.getElementById('btn4').onclick = function(){
                      sessionStorage.clear(); 
                  }
              </script>
          </body>
          </html>

1.3 - Case: value transfer between pages

Page A

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input class="name" type="text" placeholder="enter one user name"><br>
    <input class="password" type="text" placeholder="password"> <br>
    <button class="btn">next step</button>
    <script>
        // Get button
        document.querySelector('.btn').onclick = function () {
            // Get the data input by the user and store it in memory to get the user input data
            let name = document.querySelector('.name').value
            let password = document.querySelector('.password').value
            
            // Temporarily store data in memory
            sessionStorage.setItem('name', name)
            sessionStorage.setItem('password', password)
            // Jump to page B
            location.href = './Page value transfer B.html'
        }
    </script>
</body>

</html>

Page B

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input class="email" type="text" placeholder="Please enter email address"><br>
    <input class="phone" type="text" placeholder="Please enter phone number"><br>
    <button class="btn">register</button>
    <script>
        // Get button
        document.querySelector('.btn').onclick = function () {
            // Get the data entered by the user and the data of page A
            let email = document.querySelector('.email').value
            let phone = document.querySelector('.phone').value

            // Gets the data entered by the user in memory                 
            let name = sessionStorage.getItem('name')
            let password = sessionStorage.getItem('password')

            // Print input data on the console
            console.log(name, password, email, phone);
        }
    </script>
</body>

</html>

03 - how does localstorage store object type data

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="btn">Save data</button>
    <button class="btn1">Fetch data</button>
    <script>
        let obj = {
            name: 'Shuang Chen',
            age: '19'
        }
        // Gets the element of the page
        document.querySelector('.btn').onclick = function () {
            // Temporarily store the data of js object in memory
            // Convert data to json format
            let json = JSON.stringify(obj)
            // Store the converted data in memory
            sessionStorage.setItem('name', json)
        }

        document.querySelector('.btn1').onclick = function () {
            // Get the data stored by the user in memory
            let index = sessionStorage.getItem('name')
            // First, convert the user's json data to js format
            let obj = JSON.parse(index)
            console.log(obj);
        }

    </script>
</body>

</html>

Case: background management system

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body {
            background-color: cyan;
        }

        .login_form_con {
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -200px;
            margin-top: -155px;
            width: 400px;
            height: 310px;
            background-color: #edeff0;
            text-align: center;
        }

        .login_title {
            height: 50px;
            font-size: 30px;

        }

        input {
            width: 80%;
            height: 50px;
            ;
            display: block;
            margin: 20px auto;
        }
    </style>
</head>

<body>
    <div class="login_form_con">
        <div class="login_title">Background management system</div>
        <div class="login_form">
            <input type="text" class="input_txt" placeholder="mailbox/cell-phone number">
            <input type="password" class="input_pass" placeholder="password">
            <input type="submit" class="input_sub" value="Sign in">
        </div>
    </div>
    <script>
        /*
        1.Analysis requirements (interaction):
            Click the login button: (1) judge the length of user name and password: all are greater than 6. Login is successful
                           (2)If login is successful
                                (2.1)Write the user name and password into the local storage, and the user name and password will be displayed directly at the next login
                                (2.2)Jump to web page http://www.itheima.com

                
        2.Train of thought analysis (three elements of events)
            Get element: event source:
            Registering events: event types
            Event handling:
        */

        // Get page interaction elements
        let input_txt = document.querySelector('.input_txt') //mailbox
        let input_pass = document.querySelector('.input_pass')  // password
        let input_sub = document.querySelector('.input_sub') //Login button

        // Register click events for buttons
        input_sub.onclick = function () {
            // Non null judgment
            if (input_txt.value.length <= 6 || input_pass.value.length <= 6) {
                alert('Login failed')
            } else {
                // Save the user name and password entered by the user to the hard disk
                localStorage.setItem('name', input_txt.value)
                localStorage.setItem('username', input_pass.value)
                alert('Login succeeded')
                // The user logs in successfully and then jumps to the page
                location.href = 'http://www.itheima.com'
            }
        }
        // The account and password also exist when the user logs in to the page again
        // The retrieved data is directly saved to the user name and password
        input_txt.value = localStorage.getItem('name')
        input_pass.value = localStorage.getItem('username')



    </script>
</body>

</html>

Topics: Javascript