JavaScript BOM

浏览器对象模型 (BOM)

所有浏览器都支持 window 对象。它表示浏览器窗口。

所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。

全局变量是 window 对象的属性。

全局函数是 window 对象的方法。

Window 对象是BOM中所有对象的核心,除了是BOM中所有对象的父对象外,还包含一些窗口控制函数。

Window的子对象主要有如下几个:

  1. JavaScript document 对象

  2. JavaScript frames 对象:可以在 JavaScript 中创建三种消息框:警告框、确认框、提示框。

  3. JavaScript history 对象:window.history 对象包含浏览器的历史。

  • history.back() - 与在浏览器点击后退按钮相同

  • history.forward() - 与在浏览器中点击向前按钮向前相同

  1. JavaScript location 对象:window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。
  • location.hostname 返回 web 主机的域名

  • location.pathname 返回当前页面的路径和文件名

  • location.port 返回 web 主机的端口 (80 或 443)

  • location.protocol 返回所使用的 web 协议(http:// 或 https://)

  1. JavaScript navigator 对象:window.navigator 对象包含有关访问者浏览器的信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div id="example"></div>

<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;

</script>
  1. JavaScript screen 对象:window.screen 对象包含有关用户屏幕的信息。
  • screen.availWidth - 可用的屏幕宽度
  • screen.availHeight - 可用的屏幕高度

Cookies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 写入
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("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user!="" && user!=null) {
setCookie("username",user,365);
}
}
}

客户端检测

  • 能力检测:识别浏览器的能力
  • 怪癖检测:识别浏览器的特殊行为
  • 用户代理检测:
  1. 不能直接准确地使用能力监测或怪癖检测。
  2. 同一款浏览器在不同平台下具备不同的能力。
  3. 为了跟踪分析等目的需要知道确切的浏览器。