BOM
浏览器对象模型详解
1. BOM 概述
浏览器对象模型(BOM)的核心对象是 window,既是全局对象,也是浏览器窗口的表示。
2. window 对象
// 窗口尺寸
console.log(window.innerWidth); // 视口宽度
console.log(window.innerHeight); // 视口高度
// 滚动
window.scrollTo({ top: 0, behavior: 'smooth' });
window.scrollBy(0, 100);
// 定时器
setTimeout(() => {}, 1000);
setInterval(() => {}, 1000);
requestAnimationFrame(animate);
3. location 对象
console.log(location.href); // 完整 URL
console.log(location.protocol); // 'https:'
console.log(location.host); // 'example.com:8080'
console.log(location.pathname); // '/path'
console.log(location.search); // '?q=test'
console.log(location.hash); // '#section'
// URL 参数
const params = new URLSearchParams(location.search);
params.get('q'); // 'test'
// 导航
location.assign(url); // 可后退
location.replace(url); // 不可后退
location.reload(); // 重新加载
4. navigator 对象
navigator.userAgent;
navigator.language;
navigator.onLine; // 是否在线
navigator.cookieEnabled;
// 剪贴板
await navigator.clipboard.writeText('Hello');
const text = await navigator.clipboard.readText();
// 地理位置
navigator.geolocation.getCurrentPosition((pos) => {
console.log(pos.coords.latitude, pos.coords.longitude);
});
// 通知
const permission = await Notification.requestPermission();
new Notification('标题', { body: '内容' });
5. history 对象
history.back();
history.forward();
history.go(-2);
// SPA 路由
history.pushState({ page: 1 }, '', '/page1');
history.replaceState({ page: 2 }, '', '/page2');
window.addEventListener('popstate', (e) => {
console.log(e.state);
});