Skip to content

JS BOM 相关

要点速览

shell
BOM 即浏览器对象模型,用于操作浏览器窗口,顶级对象是 window。
包含五大对象:window、location、history、navigator、screen。
常用功能:页面跳转刷新、历史前进后退、获取浏览器信息、定时器、窗口尺寸、页面滚动等。
DOM 操作页面文档,BOM 操作浏览器本身,BOM 包含 DOM。

五大对象一览

shell
window:全局根对象,定时器、弹窗、btoa/atob、innerWidth 等均挂在其上
location:当前文档 URL(href / search / hash / reload 等)
history:会话历史栈(back / forward / go / SPA 路由常用的 pushState、replaceState)
navigator:环境与能力(UA、语言、权限、online、hardwareConcurrency 等)
screen:物理屏幕信息(宽高、可用区域、色深)

拓展

shell
# window 对象(顶级根对象)
window.innerWidth  # 窗口可视宽度
window.innerHeight # 窗口可视高度
window.outerWidth / window.outerHeight:浏览器窗外框尺寸(因浏览器略有差异)
window.screenX / window.screenY:窗口相对屏幕左上角偏移
window.open()   # 打开新窗口
window.close()  # 关闭窗口
window.scroll() / scrollTo / scrollBy  # 页面滚动
全局变量、全局函数、定时器,全都挂载在 window 上。

# location 对象(当前文档 URL)
location.href      # 获取/修改完整URL(赋值即跳转)
location.protocol  # 协议 http/https
location.host / hostname / port # 主机、端口拆分
location.pathname  # 路径
location.search    # ? 后查询串
location.hash      # # 后片段标识
location.reload()  # 刷新
location.assign() / replace()  # 导航(replace 不产生可返回历史条目)

# history 对象(会话历史)
history.back()    # 后退上一页
history.forward()  # 前进下一页
history.go(-1)    # 相对步进
history.pushState() / replaceState():修改地址栏且不整页刷新(前端路由基石)
注意:出于隐私与安全,不能直接读取整条历史列表内容,只能跳转。

# navigator(UA 与运行时能力)
navigator.userAgent:UA 字符串
navigator.language / languages:语言偏好
navigator.onLine:是否联网
navigator.cookieEnabled
navigator.hardwareConcurrency:逻辑 CPU
navigator.deviceMemory:近似设备内存(GB,浏览器支持情况不一)
navigator.geolocation:定位 API(需用户授权)

# screen(屏幕)
screen.width / height:屏幕分辨率
availWidth / availHeight:减去任务栏等后的可用区域
colorDepth / pixelDepth:色彩深度相关