浏览器对象
跳转到“浏览器对象”window代表浏览上下文中的窗口,并提供经典脚本的全局对象;顶层let/const和模块绑定不等于window属性。下面代码在浏览器页面中运行,环境信息随设备、隐私设置及浏览器变化。
console.log('window inner size: ' + window.innerWidth + ' x ' + window.innerHeight);console.log('appName = ' + navigator.appName);console.log('appVersion = ' + navigator.appVersion);console.log('language = ' + navigator.language);console.log('platform = ' + navigator.platform);console.log('userAgent = ' + navigator.userAgent);console.log('Screen size = ' + screen.width + ' x ' + screen.height);appName、appVersion、platform等包含兼容历史值或已弃用;UA也可伪装、缩减。判断API是否能用应做能力检测,而不是只猜浏览器名称。screen表示屏幕信息,不等于当前页面视口尺寸。
location代表当前页面URL。以下用独立URL对象演示字段,不会跳转到示例域名;换成location就是读取当前地址。
const example = new URL('http://www.example.com:8080/path/index.html?a=1&b=2#TOP');example.protocol; // 'http:',包含冒号example.host; // 'www.example.com:8080',包含非默认端口example.hostname; // 'www.example.com'example.port; // '8080'example.pathname; // '/path/index.html'example.search; // '?a=1&b=2'example.hash; // '#TOP',包含#导航示例只定义函数,由页面按钮显式调用。它会重载或离开当前页面,取消确认框时也会导航到站点根目录,这是该示例明确选择的行为。
function reloadOrHome() { if (confirm('重新加载当前页' + location.href + '?')) { location.reload(); } else { location.assign('/'); }}document是当前文档的DOM入口,Document节点包含html元素等节点。设置title可改变标签页标题;读取cookie仅能看到当前文档可访问且非HttpOnly的Cookie。
document.title = '努力学习JavaScript!';console.log(document.cookie); // 值依赖当前来源、路径及Cookie设置,不保证固定文本Cookie可以由服务器Set-Cookie或脚本设置,浏览器是否随请求发送还取决于域、路径、Secure、SameSite等条件。Cookie值并不天然加密,也不是任意user字段就能证明身份;会话凭据需由服务器验证,传输使用HTTPS。HttpOnly阻止document.cookie读取,不能理解为阻止浏览器发送。
history管理当前标签页的会话历史,并不允许脚本读取用户全部浏览记录。以下只定义函数;实际调用back/forward可能离开当前页面,也可能因没有对应记录而无变化。
function previousPage() { history.back(); }function nextPage() { history.forward(); }参考核对:Location、Document.cookie。