BOM对象
1 BOM
-
浏览器对象模型
-
BOM为我们提供了一组对象,通过这组对象可以完成对浏览器的各种操作
-
BOM对象:
- Window —— 代表浏览器窗口(全局对象)
- Navigator —— 浏览器的对象(可以用来识别浏览器)
- Location —— 浏览器的地址栏信息
- History —— 浏览器的历史记录(控制浏览器前进后退)
- Screen —— 屏幕的信息
-
BOM对象都是作为window对象的属性保存的,所以可以直接在JS中访问这些对象
2 navigator
Navigator —— 浏览器的对象(可以用来识别浏览器)
userAgent 返回一个用来描述浏览器信息的字符串
获取用户当前的浏览器信息
let sBrowser
const sUsrAg = navigator.userAgent
// The order matters here, and this may report false positives for unlisted browsers.
if (sUsrAg.indexOf("Firefox") > -1) {
sBrowser = "Mozilla Firefox"
// "Mozilla/0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
} else if (sUsrAg.indexOf("SamsungBrowser") > -1) {
sBrowser = "Samsung Internet"
// "Mozilla/0 (Linux; Android 9; SAMSUNG SM-G955F Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/9.4 Chrome/67.0.3396.87 Mobile Safari/537.36
} else if (
sUsrAg.indexOf("Opera") > -1 ||
sUsrAg.indexOf("OPR") > -1
) {
sBrowser = "Opera"
// "Mozilla/0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.106"
} else if (sUsrAg.indexOf("Trident") > -1) {
sBrowser = "Microsoft Internet Explorer"
// "Mozilla/0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
} else if (sUsrAg.indexOf("Edge") > -1) {
sBrowser = "Microsoft Edge (Legacy)"
// "Mozilla/0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
} else if (sUsrAg.indexOf("Edg") > -1) {
sBrowser = "Microsoft Edge (Chromium)"
// Mozilla/0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64
} else if (sUsrAg.indexOf("Chrome") > -1) {
sBrowser = "Google Chrome or Chromium"
// "Mozilla/0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
} else if (sUsrAg.indexOf("Safari") > -1) {
sBrowser = "Apple Safari"
// "Mozilla/0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/601.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
} else {
sBrowser = "unknown"
}
alert(`You are using: ${sBrowser}`)
3 location
3.1 常用方法
location 表示的是浏览器地址栏的信息
- 可以直接将location的值修改为一个新的地址,这样会使得网页发生跳转
location.assign()
跳转到一个新的地址location.replace()
跳转到一个新的地址(无法通过回退按钮回退)location.reload()
刷新页面,可以传递一个true来强制清缓存刷新location.href
获取当前地址
3.2 url各部分名称
Location - Web APIs | MDN (mozilla.org)
- href
- origin
- host
- hostname
port
- pathname
- search
- hash
- protocol
4 history
history.back()
:回退按钮history.forward()
:前进按钮history.go()
:可以向前跳转也可以向后跳转,传入正数向前走,传入负数向后走
go(1)
相当于forward()
go(-1)
相当于back()