BOM-浏览器对象模型

Published on

BOM 是什么,前端开发的时候肯定是都用到过,但只是缺少这个完整的概念。常用的很多对象和方法比如location,history,setTimeout...其实都是 BOM 的一部分。

BOM, Broswer Object Model 浏览器对象模型,区别于 Document Object Model,核心对象就是 window,可以说是比 DOM 更大的一个概念,document 也是 window 上的一个属性。

W3C 上有完整提及:https://www.w3schools.com/js/js_window.asp

总结梳理一下,一些关键对象或方法:

window

用于窗口信息获取,窗口管理

  • innerWidth 浏览器宽(像素)
  • innerHeight 浏览器高

一些窗口相关方法:

弹出框的交互有三种,alert,confirm,prompt

  • window.alert("sometext");

    用于警告,通知等提示

  • window.alert("sometext");

    用于确认,区别于 alert,包含确认和取消按钮,并在确认和取消的时候分别返回truefalse

  • window.prompt("sometext","defaultText");

    用于输入值的交互,在确认和取消的时候分别返回输入的 value 和 null

Timing

  • setTimeout 延迟一定时间间隔执行,通过 clearTimeout 取消

    let myVar = setTimeout(function, milliseconds);
    clearTimeout(myVar);
    
  • setInterval 固定一定时间间隔,重复执行,通过 setInterval 取消

    let myVar = setInterval(function, milliseconds);
    clearInterval(myVar);
    

history

浏览器历史,包含历史记录和一些跳转方法

  • history.back() 返回上一页
  • history.forwrod() 前进下一页
  • history.go(num) num 为正数表示前进 num 页,负数表示后退|num|页
  • history.pushState(state,title,url) 加入一条历史记录,不会立马加载
  • history.replaceState(state,title,url) 修改当前历史记录

实例属性

  • history.length 当前页面会话的 history 个数
  • history.scrollRestoration 滚动恢复属性,包含 auto(恢复用户滚动位置)和mannul(不还原用户滚动)两个值
  • history.state 当前 history 栈顶值的拷贝,也就是通过 pushState 和 replaceState 设置的 state

返回浏览器相关信息,如下几个相对常用,需要时直接在 console 中查看完整字段~

  • navigator.userAgent 客户端发送服务器的 user-agent 头部值,浏览器、系统、内核等
  • navigator.platform 平台信息
  • navigator.cookieEnabled 是否启用 Cookie
  • navigator.language 语言

location

用户获取当前地址的字段信息,导航到新地址

  • location.hash 地址 hash
  • localtion.href = 'url 地址'; 跳转到 url 地址
  • localtion.hostname 主机名
  • localtion.pathname 当前页面的路径和文件名
  • localtion.port 主机的端口
  • localtion.protocol 页面使用的 web 协议,http||https
  • location.reload() 重新加载
  • location.replace(url) 跳转到 url 并替换当前页面(当前页出栈)

screen

用户屏幕信息

  • screen.width 屏幕宽
  • screen.height 屏幕高
  • screen.availWidth 可用宽(减去系统部件尺寸)
  • screen.availHeight 可用高(减去系统部件尺寸)
  • screen.colorDepth 颜色位数
  • screen.pixelDepth 像素深度