The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
The Browser Object Model (BOM)
There are no official standards for the Browser Object Model (BOM).
說白話一點,這其實是瀏覽器的標準,跟JS沒有關係,只是要理解JS怎麼跟Brower溝通。
Since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity, it is often referred to, as methods and properties of the BOM.
The Window Object(瀏覽器物件)
The window object is supported by all browsers. It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
即使是DOM物件,其實也是BOM的子物件(或視為其一個功能屬性。
window.document.getElementById("header");
is the same as:
document.getElementById("header");
多數使用window的函數(功能/指令)時,window這個字通常被省略。
Window Size
Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).
A practical JavaScript solution (covering all browsers):
用或著來判斷使用者的版本,而用不同的指令語法
Example
var w = window.innerWidth
|| document.documentElement.clientWidth //For 舊版IE 8, 7, 6, 5:語法
|| document.body.clientWidth; //For 舊版IE 8, 7, 6, 5:語法
ar h = window.innerHeight
|| document.documentElement.clientHeight //For 舊版IE 8, 7, 6, 5:語法
|| document.body.clientHeight; //For 舊版IE 8, 7, 6, 5:語法
The example displays the browser window's height and width: (NOT including toolbars/scrollbars)
Other Window Methods
Some other methods:
- window.open() - open a new window
- window.close() - close the current window
- window.moveTo() -move the current window
- window.resizeTo() -resize the current window
The window.screen object contains information about the user's screen.
Window Screen (螢幕物件)
The window.screen object can be written without the window prefix(t前輟Window可省)
Properties:
- screen.width
- screen.height
- screen.availWidth //minus interface features like the Windows Taskbar
- screen.availHeight //minus interface features like the Windows Taskbar
- screen.colorDepth
- screen.pixelDepth
The screen.colorDepth property returns the number of bits used to display one color.
All modern computers use 24 bit or 32 bit hardware for color resolution:
- 24 bits = 16,777,216 different "True Colors"
- 32 bits = 4,294,967,296 different "Deep Colors"
Older computers used 16 bits: 65,536 different "High Colors" resulution.
Very old computers, and old cell phones used 8 bits: 256 different "VGA colors".
The #rrggbb (rgb) values used in HTML represents "True Colors" (16,777,216 different colors)
Window Screen Pixel Depth
The screen.pixelDepth property returns the pixel depth of the screen.
For modern computers, Color Depth and Pixel Depth are equal.
Window Location (伺服器當地物件)
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
The window.location object can be written without the window prefix.(前輟Window可省)
Some examples:
- window.location.href //returns the href (URL) of the current page
Result is: http://www.w3schools.com/js/js_window_location.asp - window.location.hostname //returns the domain name of the web host
Result is: www.w3schools.com - window.location.pathname //returns the path and filename of the current page
Result is:/js/js_window_location.asp - window.location.protocol //returns the web protocol used (http:// or https://)
Result is:http: (網頁使用的通訊協定) - window.location.assign() //Method load a new document “ 載入新文件”
Window History (瀏覽器的歷史記錄物件) The window.history object contains the browsers history.
The window.history object can be written without the window prefix.(前輟Window可省)
To protect the privacy of the users, there are limitations to how JavaScript can access this object.
methods: //使用這個方法來做上一頁、下一頁的控制
- history.back() - same as clicking back in the browser
- history.forward() - same as clicking forward in the browser
History.Back() and History.Forward()
The history.back() method loads the previous URL in the history list.
The history forward() method loads the next URL in the history list.
Example
Create a back button on a page:
<html>
<head>
<script>
function goBack() {
window.history.back()
}
function goForward() {
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
<input type="button" value="Forward" onclick="goForward()">
</body>
</html>
The output of the code above will be:
The window.navigator object contains information about the visitor's browser.
Window Navigator (瀏覽器版本物件)
The window.navigator object can be written without the window prefix.(前輟Window可省)
Some examples:
- navigator.appName //Result is:Netscape
- navigator.appCodeName //Result is: Mozilla
- navigator.cookieEnabled //true能讀寫cookie;false否則關閉
- navigator.product //Result is:Gecko,瀏覽器的引擊版本
- navigator.appVersion //Result is:5.0 (Windows)
- navigator.userAgent
//Result is:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0 - navigator.platform //Result is: Win32
- navigator.language //Result is: zh-TW
- navigator.javaEnabled() //Result is: false 能否JAVA
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Name is " + navigator.appName + ". Code name is " + navigator.appCodeName;
</script>
Try it Yourself »
Did you know?
IE11, Chrome, Firefox, and Safari return appName "Netscape".
Chrome, Firefox, IE, Safari, and Opera all return appCodeName "Mozilla".
Warning !!!(嚴重警告)
The information from the navigator object can often be misleading(誤導), and should not be used to detect(檢測) browser versions because:
從Navigator物件得來資料是容易誤導的,不應該用這個方法來檢測瀏覽器的版本。原因如下:
- Different browsers can use the same name
//不同瀏覽器可能用相同的名稱 - The navigator data can be changed by the browser owner
//資料能被瀏覽器的使用者改變 - Some browsers misidentify themselves to bypass site tests
//有些瀏覽器失去視別而己能繞過網站的測試 - Browsers cannot report new operating systems, released later than the browser
//不能回報一個新的作業系統、新版本的瀏覽器
JavaScript has three kind of popup boxes: 三種對話框
Alert box, Confirm box, and Prompt box.
-
Alert(); //
-
Confirm(); //OK to return ture ; Cancel
-
Prompt(); //If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
Example
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
Try it Yourself »
Line Breaks 在文字框內用 \n 可以斷行
alert("Hello\nHow are you?");
JavaScript Timing Events 定時器事件
With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
- setInterval() - executes a function, over and over again, at specified time intervals
- setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.
The setInterval() Method
The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.
Syntax
window.setInterval("javascript function", milliseconds); //(前輟Window可省)The first parameter of setInterval() should be a function.
The second parameter indicates the length of the time-intervals(間隔) between each execution.
Note: There are 1000 milliseconds in one second.
How to Stop the Execution? 停止執行
The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.
Syntax
window.clearInterval(intervalVariable) //(前輟Window可省)
To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar=setInterval("javascript function", milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
Example
Same example as above, but we have added a "Stop time" button:
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
<script>
var myVar = setInterval(function () {myTimer()}, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
Try it Yourself »
The setTimeout() Method
Syntax
window.setTimeout("javascript function", milliseconds); //(前輟Window可省)
The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
The first parameter of setTimeout() should be a function.
The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.
How to Stop the Execution?
Syntax
window.clearTimeout(timeoutVariable)
To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:
myVar=setTimeout("javascript function", milliseconds);
Then, if the function has not already been executed, you will be able to stop the execution by calling the clearTimeout() method.
What are Cookies?
Cookies let you store user information in web pages.
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information about the user":
- When a user visits a web page, his name can be stored in a cookie.
- Next time the user visits the page, the cookie "remembers" his name.
Cookies are saved in name-value pairs like:
username=John Doe
When a browser request a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.
Create a Cookie with JavaScript (DOM物件)
JavaScript can create, read, and delete cookies with the document.cookie property.
With JavaScript, a cookie can be created like this:
document.cookie="username=John Doe";
You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
Read a Cookie with JavaScript
With JavaScript, cookies can be read like this:
var x = document.cookie;
document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it:
document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"; //The old cookie is overwritten.
Delete a Cookie with JavaScript
Deleting a cookie is very simple. Just set the expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Note that you don't have to specify a cookie value when you delete a cookie.
The Cookie String
The document.cookie property looks like a normal text string. But it is not.
Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.
If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get something like:
cookie1=value; cookie2=value;
If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.
JavaScript Cookie Example
In the example to follow, we will create a cookie that stores the name of a visitor.
The first time a visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a cookie.
The next time the visitor arrives at the same page, he will get a welcome message.
For the example we will create 3 JavaScript functions:
- A function to set a cookie value
- A function to get a cookie value
- A function to check a cookie value
A Function to Set a Cookie
First, we create a function that stores the name of the visitor in a cookie variable:
Example
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Example explained:
The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).
The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.
A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:
Example
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Function explained:
Take the cookiename as parameter (cname).
Create a variable (name) with the text to search for (cname + "=").
Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).
Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length).
If the cookie is not found, return "".
A Function to Check a Cookie
Last, we create the function that checks if a cookie is set.
If the cookie is set it will display a greeting.
If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
All Together Now Example
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
//a function to get a cookie
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookie() { //a function to check a cookie
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Try it Yourself »
詳細內容可以參考: