JavaScript Screen和Navigator

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瀏覽器才有。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容