js_ex_browser
与浏览器交互:BOM 示例
Section titled “与浏览器交互:BOM 示例”浏览器对象模型(Browser Object Model,BOM)允许 JavaScript 与浏览器进行交互,而不局限于 HTML 文档本身的内容。BOM 不像 DOM 那样是标准化的,但大多数现代浏览器都实现了通用的 BOM 功能。
Window 对象
Section titled “Window 对象”The window object represents the browser window or tab. It’s the global object in client-side JavaScript. Many of its properties and methods can be accessed without explicitly writing window..
- 打开新窗口:
window.open('url', 'windowName', 'features') - 控制新窗口的外观(通过
window.open中的features字符串) - 聚焦或失去焦点:
window.focus(),window.blur() - 关闭窗口:
window.close()(通常只对通过脚本打开的窗口有效) - 检查窗口是否已关闭:
myWindow.closed(boolean) - 与父窗口/开启者窗口交互(例如,
window.opener) - 移动窗口:
window.moveTo(x, y),window.moveBy(dx, dy) - 改变窗口大小:
window.resizeTo(width, height),window.resizeBy(dw, dh) - 打印当前页:
window.print() - 滚动内容:
window.scrollTo(x, y),window.scrollBy(dx, dy)
了解更多关于 window 对象及其广泛功能的信息。
Screen 对象
Section titled “Screen 对象”The window.screen object contains information about the user’s screen.
- 屏幕宽度:
screen.width - 屏幕高度:
screen.height - 可用屏幕宽度(不包括操作系统界面,如任务栏):
screen.availWidth - 可用屏幕高度(不包括操作系统界面,如任务栏):
screen.availHeight - 颜色深度:
screen.colorDepth(每像素的位数) - 像素深度:
screen.pixelDepth(类似于颜色深度)
These information can be useful for responsive design decisions or analytics, but CSS media queries are generally preferred for styling based on screen characteristics.
Location 对象
Section titled “Location 对象”The window.location object provides information about the current URL and methods to navigate or reload the page.
- 完整 URL:
location.href(也可以设置该属性进行导航) - 协议:
location.protocol(例如,“http:”,“https:”) - 主机名:
location.hostname(例如,“www.example.com”) - 端口:
location.port - 路径名:
location.pathname(例如,“/path/to/page.html”) - 搜索字符串(查询参数):
location.search(例如,“?id=123&category=books”) - 哈希(片段标识符):
location.hash(例如,“#section1”) - 加载新文档:
location.assign('new_url')或location.href = 'new_url' - 重新加载当前页面:
location.reload(forceGet)(true 强制从服务器重新加载) - 替换当前文档(不创建历史记录条目):
location.replace('new_url')
The URL object (new URL(urlString)) is a more modern and robust way to parse and manipulate URL components.
History 对象
Section titled “History 对象”The window.history object allows interaction with the browser’s session history.
- 历史记录列表中的 URL 数量:
history.length - 后退:
history.back()(相当于浏览器后退按钮) - 前进:
history.forward() - 跳转到历史记录中的特定 URL:
history.go(n)(例如,history.go(-1)相当于back())
Modern single-page applications (SPAs) often use the History API (history.pushState(), history.replaceState(), popstate event) for more sophisticated client-side routing.
Navigator 对象
Section titled “Navigator 对象”The window.navigator object contains information about the browser itself.
- Cookies 已启用:
navigator.cookieEnabled(boolean) - 用户代理字符串:
navigator.userAgent(识别浏览器的字符串,用于特性检测时需谨慎) - 平台:
navigator.platform(例如,“Win32”,“MacIntel”) - 语言:
navigator.language或navigator.languages(用户的首选语言) - 在线状态:
navigator.onLine(boolean,指示浏览器是否有网络连接) - 地理位置:
navigator.geolocation(提供用户位置访问权,需要获得许可) - 剪贴板 API:
navigator.clipboard(用于与系统剪贴板交互,需要获得许可)
Best Practice: Instead of browser sniffing (parsing navigator.userAgent), prefer feature detection (checking if a specific object, method, or property exists and works as expected) to determine browser capabilities.
弹出框(传统)
Section titled “弹出框(传统)”JavaScript 提供了一些内置函数用于简单的模态对话框:
- Alert 弹框:
alert('message')(显示一条消息和一个“确定”按钮) - Confirm 弹框:
confirm('message')(显示一条消息、“确定”和“取消”按钮;返回true或false) - Prompt 弹框:
prompt('message', 'defaultText')(显示一条消息、一个输入框、“确定”和“取消”按钮;返回输入的字符串或null)
While still functional, these native popups are often considered intrusive and have limited styling options. Modern web applications typically use custom-styled modals or dialogs (e.g., using HTML <dialog> element or UI libraries) for a better user experience.
JavaScript 允许你在指定的时间间隔后执行代码,或以固定的间隔重复执行代码。
setTimeout(function, milliseconds, param1, param2, ...):在milliseconds毫秒后执行一次function。返回一个计时器 ID。clearTimeout(timerID):在setTimeout()执行前取消它。setInterval(function, milliseconds, param1, param2, ...):每隔milliseconds毫秒重复执行function。返回一个间隔 ID。clearInterval(intervalID):停止一个setInterval()。
For smooth animations, requestAnimationFrame(callback) is preferred over setTimeout or setInterval. It tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.
客户端存储:Cookies 和 Web Storage
Section titled “客户端存储:Cookies 和 Web Storage”Cookies(document.cookie)是浏览器存储在用户计算机上的小段数据。它们会随向同一域的每个 HTTP 请求一起发送。Although useful for session management, they have size limitations and can impact performance if overused.
Modern alternatives for client-side storage include the Web Storage API:
localStorage:存储没有过期时间的数据。数据即使浏览器窗口关闭再重新打开也仍然保留。(例如,localStorage.setItem('key', 'value');,localStorage.getItem('key');)sessionStorage:仅为当前会话存储数据。当浏览器标签页关闭时,数据会被清除。
Web Storage offers larger storage capacity and a simpler API compared to cookies for client-side data that doesn’t need to be sent with every HTTP request. For more complex client-side data needs, IndexedDB provides a transactional database system.