JavaScript BOM (Browser Object Model) 详解
1. BOM 介绍
BOM (Browser Object Model) 是浏览器对象模型,它提供了独立于内容而与浏览器窗口进行交互的对象。BOM的核心对象是window,它表示浏览器的一个实例。
BOM包含的主要对象:
- window:浏览器窗口
- navigator:浏览器信息
- screen:显示器信息
- history:浏览器历史记录
- location:URL信息
2. window 对象
window对象是BOM的核心,所有全局JavaScript对象、函数和变量自动成为window对象的成员。
全局变量和函数
var globalVar = "我是全局变量"; // 等同于 window.globalVar
function globalFunc() {
console.log("我是全局函数");
}
// 等同于 window.globalFunc()
3. 全局作用域
在全局作用域中声明的变量和函数都会成为window对象的属性和方法。
// 示例:全局作用域
var a = 10;
console.log(window.a); // 10
function test() {
console.log("测试函数");
}
window.test(); // "测试函数"
4. 系统对话框
浏览器提供了三种系统对话框:
- alert()
- confirm()
- prompt()
alert() 示例
// 显示警告框
window.alert("这是一个警告信息"); // 简写为 alert("这是一个警告信息")
confirm() 示例
// 显示确认框,返回布尔值
let isConfirmed = confirm("你确定要删除吗?");
if (isConfirmed) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
prompt() 示例
// 显示提示框,返回用户输入的字符串
let userName = prompt("请输入你的名字", "默认名字");
if (userName !== null) {
console.log(`你好, ${userName}`);
} else {
console.log("用户取消了输入");
}
5. 打开和关闭窗口
window.open() 方法
// 打开新窗口
let newWindow = window.open(
"https://www.example.com", // URL
"exampleWindow", // 窗口名称
"width=400,height=300" // 窗口特性
);
// 检查窗口是否被阻止
if (newWindow === null) {
alert("弹出窗口被浏览器阻止了!");
}
window.close() 方法
// 关闭当前窗口
function closeCurrentWindow() {
if (confirm("确定要关闭窗口吗?")) {
window.close();
}
}
// 关闭之前打开的窗口
if (newWindow && !newWindow.closed) {
newWindow.close();
}
6. 窗口位置
获取窗口位置
// 跨浏览器获取窗口位置
let windowLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
let windowTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
console.log(`窗口位置 - 左: ${windowLeft}, 上: ${windowTop}`);
移动窗口位置
// 移动窗口到指定位置
function moveWindowTo(x, y) {
window.moveTo(x, y); // 绝对位置
// window.moveBy(dx, dy); // 相对当前位置移动
}
// 使用示例
moveWindowTo(100, 200);
7. 窗口大小
获取窗口大小
// 跨浏览器获取视口大小
let viewportWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
console.log(`视口大小 - 宽: ${viewportWidth}, 高: ${viewportHeight}`);
// 获取屏幕大小
console.log(`屏幕大小 - 宽: ${screen.width}, 高: ${screen.height}`);
调整窗口大小
// 调整窗口大小
function resizeWindow(width, height) {
window.resizeTo(width, height); // 绝对大小
// window.resizeBy(dWidth, dHeight); // 相对当前大小调整
}
// 使用示例
resizeWindow(500, 400);
8. 框架操作
访问框架
<!-- HTML框架示例 -->
<frameset cols="25%,50%,25%">
<frame name="leftFrame" src="left.html">
<frame name="mainFrame" src="main.html">
<frame name="rightFrame" src="right.html">
</frameset>
// 访问框架
let leftFrame = window.frames["leftFrame"]; // 或 window.leftFrame
// 在框架中访问父窗口
if (window.parent !== window) {
// 当前窗口是框架
console.log("当前窗口是框架");
}
// 访问顶层窗口
let topWindow = window.top;
iframe 操作
<!-- iframe示例 -->
<iframe id="myIframe" src="https://www.example.com" width="600" height="400"></iframe>
// 获取iframe元素
let iframe = document.getElementById("myIframe");
// 访问iframe内容
iframe.onload = function() {
try {
let iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
console.log("iframe加载完成", iframeDoc.title);
} catch (e) {
console.log("跨域访问被拒绝");
}
};
// 改变iframe src
function changeIframeSrc(url) {
iframe.src = url;
}
9. 示例:第三方跳转
/**
* 第三方跳转函数
* @param {string} url - 要跳转的URL
* @param {string} [target="_blank"] - 打开方式 (_blank, _self, _parent, _top)
* @param {Object} [features] - 窗口特性 (width, height等)
*/
function redirectToThirdParty(url, target = "_blank", features = null) {
// 安全检查 - 验证URL
if (!url || typeof url !== "string") {
console.error("无效的URL");
return;
}
// 简单的URL格式验证
try {
new URL(url); // 如果URL无效会抛出错误
} catch (e) {
console.error("URL格式不正确:", e.message);
return;
}
// 如果是新窗口且有特性参数
if (target === "_blank" && features) {
let featuresStr = Object.entries(features)
.map(([key, value]) => `${key}=${value}`)
.join(",");
window.open(url, target, featuresStr);
} else {
// 普通跳转
window.location.href = url;
}
// 记录跳转
console.log(`跳转到第三方网站: ${url}`);
}
// 使用示例1: 简单跳转
redirectToThirdParty("https://www.google.com");
// 使用示例2: 在新窗口中打开并指定大小
redirectToThirdParty(
"https://www.baidu.com",
"_blank",
{ width: 800, height: 600 }
);
// 使用示例3: 在当前窗口打开
redirectToThirdParty("https://github.com", "_self");
防止跳转劫持的安全措施
// 安全跳转函数 - 防止跳转劫持
function safeRedirect(url, delay = 0) {
// 显示用户控制界面
const redirectInfo = document.createElement("div");
redirectInfo.style.position = "fixed";
redirectInfo.style.top = "0";
redirectInfo.style.left = "0";
redirectInfo.style.width = "100%";
redirectInfo.style.backgroundColor = "#ffeb3b";
redirectInfo.style.padding = "10px";
redirectInfo.style.textAlign = "center";
redirectInfo.style.zIndex = "1000";
redirectInfo.style.boxShadow = "0 2px 5px rgba(0,0,0,0.2)";
redirectInfo.innerHTML = `
<p>即将跳转到: ${url}</p>
<button id="continueRedirect">继续跳转</button>
<button id="cancelRedirect">取消跳转</button>
<span id="countdown">${delay}</span>秒后自动跳转
`;
document.body.appendChild(redirectInfo);
// 倒计时功能
let remaining = delay;
const countdownElement = document.getElementById("countdown");
const countdownInterval = setInterval(() => {
remaining--;
countdownElement.textContent = remaining;
if (remaining <= 0) {
clearInterval(countdownInterval);
performRedirect();
}
}, 1000);
// 按钮事件
document.getElementById("continueRedirect").addEventListener("click", () => {
clearInterval(countdownInterval);
performRedirect();
});
document.getElementById("cancelRedirect").addEventListener("click", () => {
clearInterval(countdownInterval);
document.body.removeChild(redirectInfo);
});
function performRedirect() {
document.body.removeChild(redirectInfo);
window.location.href = url;
}
}
// 使用示例
safeRedirect("https://www.example.com", 5);
以上代码提供了BOM相关功能的全面实现,包括窗口操作、对话框、框架操作等,并且包含了详细的注释和安全措施。
以下是基于BOM(浏览器对象模型)的具体开发案例,结合了窗口操作、对话框、定时器等核心功能,并附有详细代码注释:
一、窗口操作案例
1. 新窗口创建与内容注入
// 创建新窗口并写入内容
const newWindow = window.open('', 'demoWindow', 'width=600,height=400');
if (newWindow) {
newWindow.document.write('<h1>新窗口内容</h1><p>通过BOM动态生成</p>');
// 5秒后自动关闭窗口
setTimeout(() => newWindow.close(), 5000);
} else {
alert('弹出窗口被浏览器阻止!');
}
功能:通过window.open()
创建新窗口并注入HTML内容,5秒后自动关闭。
2. 窗口居中显示
function openCenteredWindow(url, width, height) {
const left = (screen.width - width) / 2;
const top = (screen.height - height) / 2;
window.open(url, '', `width=${width},height=${height},left=${left},top=${top}`);
}
功能:计算屏幕居中坐标,打开指定大小的窗口。
二、对话框与用户交互
1. 表单提交确认
document.querySelector('form').addEventListener('submit', (e) => {
const isConfirmed = confirm('确认提交数据吗?');
if (!isConfirmed) e.preventDefault(); // 取消提交
});
功能:提交前弹出确认框,避免误操作。
2. 输入验证提示
const age = prompt('请输入您的年龄', '18');
if (age >= 18) {
alert('欢迎访问成人内容!');
} else {
window.location.href = 'https://child-safe-site.com';
}
功能:通过prompt
获取用户输入并跳转不同页面。
三、定时器与动态效果
1. 倒计时跳转页面
let countdown = 10;
const timer = setInterval(() => {
document.getElementById('countdown').textContent = `${countdown}s后跳转`;
if (countdown-- <= 0) {
clearInterval(timer);
window.location.href = 'https://example.com';
}
}, 1000);
功能:显示倒计时并自动跳转,常用于广告页或登录后重定向。
2. 防抖窗口 resize 事件
let resizeTimer;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
console.log('窗口稳定大小:', window.innerWidth, window.innerHeight);
}, 200);
});
功能:避免频繁触发resize事件,优化性能。
四、框架与跨窗口通信
1. 父窗口与iframe交互
<iframe id="myFrame" src="child.html"></iframe>
<script>
const frame = document.getElementById('myFrame');
frame.onload = () => {
// 向iframe发送消息
frame.contentWindow.postMessage('Hello from parent!', '*');
};
// 接收子窗口消息
window.addEventListener('message', (e) => {
if (e.origin === 'https://trusted-domain.com') {
console.log('子窗口消息:', e.data);
}
});
</script>
功能:使用postMessage
实现跨域安全通信。
五、实战案例:拖拽模态框
// 获取模态框元素
const modal = document.querySelector('.modal');
const header = modal.querySelector('.modal-header');
let isDragging = false;
let offsetX, offsetY;
header.addEventListener('mousedown', (e) => {
isDragging = true;
offsetX = e.clientX - modal.offsetLeft;
offsetY = e.clientY - modal.offsetTop;
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
modal.style.left = `${e.clientX - offsetX}px`;
modal.style.top = `${e.clientY - offsetY}px`;
});
document.addEventListener('mouseup', () => isDragging = false);
功能:通过计算鼠标偏移量实现模态框拖拽。
六、安全跳转案例
function safeRedirect(url) {
if (url.startsWith('https://trusted.com')) {
window.location.href = url;
} else {
console.error('拒绝跳转到非信任域名!');
}
}
功能:防止恶意重定向攻击。
以上案例覆盖了BOM的核心应用场景,可根据实际需求调整参数或扩展功能。更多高级用法(如结合Electron开发桌面应用)可参考Electron官方文档。