A Preliminary Study of BOM in JavaScript

1. Window browser object model

1. Browser Object Model (BOM)

The Browser Object Model (BOM) gives Javascript the ability to "talk" to the browser.

2.Window object

  • All browsers support the window object. It represents a browser window.
  • All JavaScript global objects, functions, and variables are automatically members of the window object.
  • Global variables are properties of the window object.
  • Global functions are methods of the window object.
    Even the document of the HTML DOM is one of the properties of the window object:
 window.document.getElementById("header");
 //与此相同
 document.getElementBuId("header");

3.Window size

There are three ways to determine the size of the browser window.
For Internet Explorer, Chrome, Firefox, Opera, and Safari:

window.innerHeight - 浏览器窗口的内部高度(包括滚动条)
window.innerWidth - 浏览器窗口的内部宽度(包括滚动条)

For Internet Explorer 8, 7, 6, 5:

document.documentElement.clientHeight
document.documentElement.clientWidth

or

document.body.clientHeight
document.body.clientWidth

Covers all browser implementations (this example shows the height and width of the browser window, excluding toolbars/scrollbars)

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight ||document.body.clientHeight;

4. Other Window methods

window.open()  //打开新窗口
window.close()  //关闭当前窗口
window.moveTo()  //移动当前窗口
window.resizeTo()  //调整当前窗口的尺寸

2. Window screen

The window.screen object contains information about the user's screen

1.Window Screen

The window.screen object does not need to use the window prefix when writing.
Some properties:

screen.availWidth //可用屏幕的宽度
screen.availHeight  //可用屏幕高度

2. Window Screen available width

The screen.availWidth property returns the width of the visitor's screen in pixels, minus interface features such as window taskbars.
Example:

<script>
    document.write("可用宽度: " + screen.availWidth);
</script>

3. Window Screen available height

The screen.availHeight property returns the height of the visitor's screen in pixels, minus interface features such as window taskbars.
Example:

<script>
    document.write("可用高度: " + screen.availHeight);
</script>

3. Window Location

The window.location object is used to get the address (URL) of the current page and redirect the browser to a new page.

1. Window Location

The window.location object can be written without the window prefix. Some examples:

location.hostname //返回 web 主机的域名
location.pathname //返回当前页面的路径和文件名
location.port //返回 web 主机的端口 (80 或 443)
location.protocol //返回所使用的 web 协议(http:// 或 https://)

2. Window Location Href

The location.href property returns the URL of the current page.

<script>

    document.write(location.href);

</script>

3. Window Location Pathname

The location.pathname property returns the pathname of the URL.

<script>
    document.write(location.pathname);
</script>

4. Window Location Assign

The location.assign() method loads a new document.

<input type="button" value="加载新文档" onclick="newDoc()">
<script>
    function newDoc() {
     
     
        window.location.assign("http://www.w3cschool.cc");
    }
</script>

3. Window History

The window.history object contains the browser's history.

1. Window History

The window.history object can be written without the window prefix.
To protect user privacy, the methods that JavaScript can use to access this object are restricted.
Some methods:

history.back()    //与在浏览器点击后退按钮相同
history.forward()  //与在浏览器中点击向前按钮相同

2. Window History Back

The history.back() method loads the previous URL in the history list. This is the same as hitting the back button in the browser:

<input type="button" value="Back" onclick="goBack()">
<script>
    function goBack() {
     
     
        window.history.back();
    }
</script>

3. Window History Forward

The history forward() method loads the next URL in the history list. This is the same as hitting the forward button in the browser:

<input type="button" value="Forward" onclick="goForward()">
<script>
    function goForward() {
     
     
        window.history.forward();
    }
</script>

四、JavaScript Window Navigator

The window.navigator object contains information about the visitor's browser.

1. Window Navigator

The window.navigator object can be written without the window prefix.

<div id="example"></div>
<script>
    txt = "<p>浏览器代号: " + navigator.appCodeName + "</p>";
    txt+= "<p>浏览器名称: " + navigator.appName + "</p>";
    txt+= "<p>浏览器版本: " + navigator.appVersion + "</p>";
    txt+= "<p>启用Cookies: " + navigator.cookieEnabled + "</p>";
    txt+= "<p>硬件平台: " + navigator.platform + "</p>";
    txt+= "<p>用户代理: " + navigator.userAgent + "</p>";
    txt+= "<p>用户代理语言: " + navigator.systemLanguage + "</p>";
    document.getElementById("example").innerHTML=txt;
</script>

2. WARNING!!!

The information from the navigator object is misleading and should not be used to detect browser version because:

  • navigator data can be changed by the browser user
  • Some browsers misidentify the test site
  • Browsers cannot report new operating systems released later than the browser

3. Browser detection

Since the navigator can mislead browser detection, using object detection can be used to sniff different browsers.
Since different browsers support different objects, you can use objects to detect browsers. For example, you can identify Opera because only Opera supports the property "window.opera".
example:

if(window.opera) {
    ...some action...
}

Five, javascript timing events

JavaScript executes code after a set interval, which we call timing events.

1. JavaScript timing events

By using JavaScript, we have the ability to execute code after a set time interval, rather than immediately after the function is called. We call these timing events.
Using timed events in JavaScript is easy, the two key methods are:

  • setInterval() - Executes the specified code continuously for the specified number of milliseconds.
  • settimeout() - Executes the specified code after pausing for the specified number of milliseconds.

2. setInterval () method

setInterval() executes the specified code continuously for the specified number of milliseconds.
grammar:

window.setInterval("javascript function", milliseconds);

The window.setInterval() method can directly use the function setInterval() without using the window prefix.
The first parameter of setInterval() is a function.
Second parameter interval in milliseconds
Note: 1000 milliseconds is one second.
Example:

var myVar = setInterval(function() {
    
    myTimer()}, 1000);
function myTimer() {
    
    
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

3. How to stop execution?

The clearInterval() method is used to stop the function code executed by the setInterval() method.
grammar

window.clearInterval(intervalVariable)

The window.clearInterval() method can directly use the function clearInterval() without using the window prefix.
To use the clearInterval() method, you must use a global variable when creating the timing method:

myVar = setInterval(function, milliseconds);

Example:

<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>

<script>
    var myVar = setInterval(function() {
     
     myTimer()}, 1000);
    function myTimer() {
     
     
        var d = new Date();
        var t = d.toLocaleTimeString();
        document.getElementById("demo").innerHTML=t;
    }
    function myStopFunction() {
     
     
        clearInterval(myVar);
    }
</script>

4. setTimeout() method

grammar:

window.setTimeout(function, milliseconds);

The setTimeout() method returns a value. In the above statement, the value is stored in a variable named t. If you want to cancel this setTimeout(), you can use this variable name to specify it.
The first argument to setTimeout() is a string containing the JavaScript statement. This statement might be something like "alert('5 seconds!')", or a call to a function like alertMsg()". The
second parameter indicates how many milliseconds from now to execute the first parameter.
Hint: 1000 milliseconds equals one seconds.
Example:

setTimeout(function() {
    
    
    alert("Hello");
}, 3000);

5. How to stop execution?

The clearTimeout() method is used to stop executing the function code of the setTimeout() method.
grammar:

window.clearTimeout(timeoutVariable)

The window.clearTimeout() method can be used without the window prefix.
To use the clearTimeout() method, you must use a global variable in the creation timeout method (setTimeout):

myVar = setTimeout(function, milliseconds);

If the function has not been executed, you can use the clearTimeout() method to stop executing the function code.
Example:

var myVar;

function myFunction(){
    
    
    myVar=setTimeout(function(){
    
    alert("Hello")},3000);
}

function myStopFunction() {
    
    
    clearTimeout(myVar);
}

六、JavaScript Cookie

Cookies are used to store user information on web pages.

1. What are cookies?

A cookie is some data, stored in a text file on your computer.
When the web server sends a web page to the browser, the server does not record the user's information after the connection is closed.
The role of cookies is to solve "how to record client user information":

  • When a user visits a web page, his name can be recorded in a cookie.
  • When the user visits the page next time, the user visit record can be read in the cookie.

Cookies are stored as name/value pairs, as follows:

username=John Doe

When a browser requests a web page from a server, the cookie belonging to that page is added to the request. The server obtains user information in this way.

2. Create cookies using Javascript

JavaScript can use the document.cookie property to create, read, and delete cookies.
In JavaScript, creating a cookie looks like this:

doucment.cookie = "username=John Doe";

You can also add an expiration time (in UTC or GMT time) to the cookie. By default, cookies are deleted when the browser is closed:

document.cookir="username=John Doe; expires=Thu, 18 Dec 2015 12:00:00 GMT";

You can tell the browser the path to the cookie using the path parameter. By default, cookies belong to the current page.

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

3. Use Javascript to read cookies

In JavaScript, the following code can be used to read cookies:

var x = document.cookie;

In JavaScript, modifying a cookie is similar to creating a cookie, as follows:

document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

Old cookies will be overwritten.

Deleting cookies is very simple. You just need to set the expires parameter to a previous time, as shown below, set to Thu, 01 Jan 1970 00:00:00 GMT:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

Note that you don't have to specify a cookie value when you delete.

The document.cookie property looks like a normal text string, but it's not.
Even if you write a complete cookie string in document.cookie, when you re-read the cookie information, the cookie information is displayed in the form of name/value pairs.
If you set a new cookie, the old cookie will not be overwritten. The new cookie will be added to document.cookie, so if you re-read document.cookie you will get data like this:

cookie1=value; cookie2=value;

In the following example we will create a cookie to store the visitor's name.

First, a visitor visits a web page, and he will be asked to fill in his name. This name will be stored in the cookie.

The next time a visitor visits the page, he will see a welcome message.

In this example we will create 3 JavaScript functions:

1) Function to set cookie value
2) Function to get cookie value
3) Function to detect cookie value

First, we create a function to store the visitor's name:

function setCookie(cname, cvalue, exdays) {
    
    
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

Function analysis:
In the above function parameters, the name of the cookie is cname, the value of the cookie is cvalue, and the expiration time of the cookie is set to expires.
This function sets the cookie name, cookie value, and cookie expiration time.

Then, we create a function user to return the value of the specified cookie:

function getCookie(cname) {
    
    
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length, c.length);
    }
    return "";
} 

Function analysis:

The parameter for the cookie name is cname.

Create a text variable for retrieving the specified cookie: cname + "=".

Use a semicolon to split the document.cookie string, and assign the split string array to ca (ca = document.cookie.split(';')).

Loop through the ca array (i=0;i<ca.length;i++), then read each value in the array and trim leading and trailing spaces (c=ca[i].trim()).

If found cookie(c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length).

If no cookie is found, return "".

Finally, we can create a function that detects whether a cookie was created.

If a cookie is set, a greeting message will be displayed.

If no cookie is set, a popup will be displayed asking for the visitor's name, and the setCookie function will be called to store the visitor's name for 365 days:

function checkCookie() {
    
    
    var username=getCookie("username");
    if(username!="") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:","");
        if(username!="" && username!=null) {
            setCookie("username", username,365);
        }
    }
}

11. Complete example

function setCookie(cname,cvalue,exdays){
    
    
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname){
    
    
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
    }
    return "";
}
function checkCookie(){
    
    
    var user=getCookie("username");
    if (user!=""){
        alert("欢迎 " + user + " 再次访问");
    }
    else {
        user = prompt("请输入你的名字:","");
          if (user!="" && user!=null){
            setCookie("username",user,30);
        }
    }
}

Guess you like

Origin blog.csdn.net/Jason_first/article/details/79262856