screen和navigator是window對象下的兩個對象,可以不帶window.直接使用screen和navigator。screen包含瀏覽器窗口的信息,navigator包含瀏覽器及系統(tǒng)的信息。
screen對象
window.screen 對象包含有關(guān)用戶屏幕的信息,使用的時候可以不帶window。下面代碼我們在控制臺打印一下screen,screen對象主要有的是尺寸的屬性。
console.log(screen);//Screen{...}
窗口尺寸
screen.width - 屏幕寬度
screen.height - 屏幕高度
screen.availWidth - 可用的屏幕寬度
screen.availHeight - 可用的屏幕高度
console.log(screen.width);//1536
console.log(screen.height);//864
console.log(screen.availWidth);//1536
console.log(screen.availHeight);//824
navigator對象
window.navigator對象和上面的screen對象差不多,window.navigator 對象包含有關(guān)訪問者瀏覽器的信息,window.navigator對象在編寫時也可以不使用 window 這個前綴。
console.log(navigator);//Navigator{...}
navigator對象包含的信息明顯更多一些,但是navigator對象的信息具有誤導性,因為navigator的數(shù)據(jù)可能會被更改,或者瀏覽器識別錯誤等。一些常見的navigator屬性信息:
- navigator.appCodeName - 瀏覽器代號
- navigator.appName - 瀏覽器名稱
- navigator.appVersion - 瀏覽器版本
- navigator.cookieEnabled - Cookies是否啟用
- navigator.platform - 硬件平臺
- navigator.userAgent - 用戶代理
- navigator.language - 用戶代理語言
console.log(navigator.appCodeName);//Mozilla
console.log(navigator.appName);//Netscape
console.log(navigator.appVersion);//5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
console.log(navigator.cookieEnabled);//true
console.log(navigator.platform);//win32
console.log(navigator.userAgent);//Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
console.log(navigator.language);//zh-CN
由于 navigator 可誤導瀏覽器檢測,使用對象檢測可用來嗅探不同的瀏覽器,比如window.opera對象只有Opera瀏覽器才有。