浏览器能力实战:Window、存储、文件与定位
做一个“旅行准备”页面,需求清单是这样的:地址栏里留着当前选中的城市,方便把链接发给同伴;刷新以后还记得用户选的深色主题;允许导入一份本地行程文件;用户点了按钮才查看当前位置;页面里嵌了一张地图,它和主页面要互相传消息,但不能让陌生页面也能指挥你。
五件事互不相干,却都不归 JavaScript 语言管。语言只负责变量、函数、对象这些逻辑;地址栏、历史记录、本地存储、文件选择器、定位硬件,都是浏览器通过 window、location、history、navigator、Storage、FileReader 等对象借给网页的。借出去的东西有门槛:有的要用户点头,有的只在安全连接下可用,有的随时会失败。本章逐个看这些对象怎么用,更要看它们什么时候出问题,以及哪些数据绝对不能往里放。
本章代码运行在浏览器页面里,请通过本地开发服务器打开。Node.js 没有标签页,不存在同一种 window、document、location 或 localStorage。其中 URL、URLSearchParams、setTimeout、globalThis 在 Node 里也有,对应示例已用 Node.js 实际运行并核对输出;依赖页面的示例只检查了语法,并会注明运行环境。
学习路线
完成本章后,你应该能够:
- 说明
window、DOM 与 BOM 的关系,避免污染全局命名空间; - 用
URL与location可靠地解析、修改和跳转地址; - 用 History API 维护单页界面的地址,并正确响应前进与后退;
- 解释定时器为什么只保证“最早执行时间”,并分清几种视口尺寸;
- 在 cookie、
localStorage与sessionStorage之间做选择; - 安全地读取用户主动选择的文件,处理定位的权限与错误;
- 用
postMessage()在 iframe 或新窗口之间建立受约束的通信。
window:浏览器能力的总入口
打开一个页面,浏览器就创建一个浏览上下文(browsing context):顶层页面是一个,每个 iframe 是一个,脚本打开的新窗口又是一个。每个上下文有自己的全局对象,在普通网页脚本里它就是 window。

window 是当前浏览上下文的总入口,但它不等于 JavaScript 语言本身。
常用的名字几乎都能从它身上找到:
window.document;
window.location;
window.history;
window.navigator;
window.localStorage;
window.setTimeout;所以在页面里,setTimeout(showTip, 1000) 和 window.setTimeout(showTip, 1000) 调的是同一个东西,前面的 window. 可以省略,因为全局变量查找最终会落到全局对象上。
document 是 DOM 的入口,描述页面文档树。BOM(Browser Object Model)则只是一个习惯叫法,指地址栏、会话历史、浏览器信息、窗口尺寸、定时器这些“文档之外”的能力。它没有独立的语法,也没有单独的规范,别把它当成一门和 DOM 并列的技术。
在控制台里认一认
打开开发者工具的 Console,先执行 console.dir(window),展开对象,找到 document、location、history、navigator 和 innerWidth。再做几个只读观察:
console.log(window === globalThis);
console.log(window.document === document);
console.log(window.location.href);
console.log(window.innerWidth, window.innerHeight);在普通网页脚本顶层,globalThis 就是 window。写通用库时用 globalThis 更稳,Web Worker 里全局对象叫 self,Node.js 里没有 window,而 globalThis 在这些环境里都指向各自的全局对象。
第 14.1 题 · 单选题
顶层变量别当公共储物柜
传统(非模块)脚本里,顶层的 var 和函数声明会变成 window 的属性:
<script>
var currentUser = "小虎";
function renderUser() {
document.body.textContent = currentUser;
}
console.log(window.currentUser); // 小虎
</script>顶层 let、const 不会长到 window 上,<script type="module"> 里的顶层声明也只属于模块自己。但页面上常有好几份脚本,其中还可能有广告、统计之类不是你写的代码。靠“名字大概不会重”来保平安,迟早撞车。把逻辑放进模块或函数,只暴露确实需要的入口,才是长久之计。
第 14.2 题 · 判断题
URL 与 location:读地址,也要管住跳转
window.location 是当前页面的 Location 对象。它长得像一个字符串,其实把地址拆成了几段,还带着导航方法。以这个地址为例:
https://learn.example:8443/course/window?chapter=14&mode=lab#timers解析交给 URL 对象
有人习惯 location.search.split("&") 再 split("="),遇到 %E4%B8%8A、重复参数、值里带 = 就会出错。URL 与 URLSearchParams 已经替你处理好了:
const url = new URL(
"https://learn.example:8443/course/window?chapter=14&mode=lab#timers"
);
console.log(url.pathname); // /course/window
console.log(url.searchParams.get("chapter")); // 14
url.searchParams.set("mode", "review");
url.hash = "storage";
console.log(url.href);
// https://learn.example:8443/course/window?chapter=14&mode=review#storage这段代码在 Node.js 里同样可以运行,输出如注释所示。传相对地址时必须给基准,页面里通常拿当前地址做基准:
const detailUrl = new URL("./detail?id=42", location.href);
console.log(detailUrl.href);运行环境:浏览器页面(用到 location)。如果页面地址是前面那个例子,这里得到 https://learn.example:8443/course/detail?id=42。
searchParams.get() 找不到键返回 null。同名参数可以出现多次,比如 ?tag=a&tag=b,要全部读出来得用 getAll():
const tags = new URL("https://x.test/?tag=a&tag=b").searchParams;
console.log(tags.get("tag")); // a
console.log(tags.getAll("tag")); // [ 'a', 'b' ]第 14.3 题 · 填空题
assign、replace、reload:差别在历史记录
location.assign("/login");
location.replace("/login");
location.reload();给 location.href 赋值,效果和 assign() 接近。三者调用后当前文档都会离开或刷新,练习前先保存好内容。
登录成功后跳回原页面是最典型的场景:用 replace,用户点后退就不会又看到登录表单。但跳转目标常常来自查询参数,比如 /login?next=/orders,这时千万不能照单全收,否则攻击者发一条 ?next=https://evil.example 的链接,你的站点就成了钓鱼跳板(开放重定向):
function safeRedirect(rawTarget) {
const target = new URL(rawTarget, location.origin);
if (target.origin !== location.origin) {
throw new Error("只允许站内跳转");
}
location.replace(target.href);
}先按当前源解析:相对地址会落在本站,写成 https://evil.example/... 的绝对地址则 origin 不同,被拒绝。更严格的项目还会把可去的路径列成白名单。
第 14.4 题 · 判断题
History:改地址,不重载整页
history 管的是当前标签页(或 frame)走过的会话历史。它能前后移动,也能在不重载页面的情况下改写当前地址,单页应用的“路由”靠的就是后一项。

location 看的是当前地址;history 管的是这个标签页走过的路径。
移动方法很直白:
history.back(); // 约等于 go(-1)
history.forward(); // 约等于 go(1)
history.go(-2); // 向后退两项浏览器不会把完整的历史地址列表交给网页。脚本只能读 history.length、移动位置、读当前项的 history.state,无法枚举用户去过哪些地方,这是隐私保护。
pushState 与 replaceState
单页界面切换视图时,同步改一下地址栏,用户才能刷新、收藏、转发:
function showView(view) {
document.querySelector("#view").textContent = `当前视图:${view}`;
}
function navigateTo(view) {
const nextUrl = new URL(location.href);
nextUrl.searchParams.set("view", view);
history.pushState({ view }, "", nextUrl);
showView(view);
}
window.addEventListener("popstate", (event) => {
const view =
event.state?.view ??
new URL(location.href).searchParams.get("view") ??
"home";
showView(view);
});运行环境:浏览器页面,且文档里有 #view 元素。
pushState(state, "", url) 新增一项,replaceState() 改写当前项、不增加 history.length。两个约束要记住:URL 必须与当前文档同源,state 必须能被结构化克隆,DOM 节点和函数放不进去。
初学者最容易漏掉的一点:这两个方法只改历史和地址,不触发 popstate,也不会更新 DOM。上面代码里 navigateTo 要自己调 showView;popstate 只在用户前进、后退到另一个历史项时才触发。还要留一个“没有 state”的兜底,因为用户可能是刷新后直接打开带参数的链接,这时 event.state 为空,只能从 URL 里恢复。
下面的实验台把 location、history.length、state 摆在一起,多点几下前进后退,看每一步哪个值变了。
第 14.5 题 · 多选题 · 选出所有正确项
navigator 与定位:先问能力,再问用户
navigator 汇集浏览器环境暴露的信息和入口。判断功能能不能用,做能力检测,不要靠浏览器名字猜:
if ("geolocation" in navigator) {
console.log("可以请求定位");
} else {
console.log("当前环境没有提供定位 API");
}
if ("clipboard" in navigator) {
console.log("检测到剪贴板入口");
}属性存在只说明“有入口”,不保证调用成功:安全上下文、用户授权、设备硬件、浏览器策略都能拒绝你。navigator.userAgent 可以用来排查兼容问题,不适合决定业务流程,它会被简化、冻结甚至伪装,能力检测加降级方案可靠得多。
第 14.6 题 · 单选题
请求一次当前位置
定位属于敏感能力:通常要求 HTTPS 这样的安全上下文(开发时 localhost 一般被当作例外),而且由用户决定给不给。
const output = document.querySelector("#position");
const locateButton = document.querySelector("#locate");
locateButton.addEventListener("click", () => {
if (!("geolocation" in navigator)) {
output.textContent = "当前浏览器不支持定位。";
return;
}
output.textContent = "正在请求位置…";
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
output.textContent =
`纬度 ${latitude.toFixed(5)},` +
`经度 ${longitude.toFixed(5)},` +
`精度约 ${Math.round(accuracy)} 米`;
},
(error) => {
const messages = {
1: "用户拒绝了定位权限。",
2: "当前无法获得位置。",
3: "定位请求超时。"
};
output.textContent = messages[error.code] ?? "定位失败。";
},
{
enableHighAccuracy: false,
timeout: 8000,
maximumAge: 60_000
}
);
});运行环境:浏览器页面,文档里有 #position 与 #locate。
成功回调拿到 GeolocationPosition。coords.latitude、coords.longitude、coords.accuracy 都是数字;accuracy 是以米计的估计误差半径,不是“小数点后几位都准”的承诺。altitude、altitudeAccuracy、heading、speed 则可能是 null。
三个选项各有取舍:
enableHighAccuracy: true是偏好,可能更慢更耗电,也不保证更准;timeout限制这一次最多等多久;maximumAge允许复用多旧的缓存位置,0表示不接受缓存。
需要持续跟踪就用 watchPosition(),把返回的 id 存下来,不再需要时 clearWatch(id)。别在页面一加载就弹定位请求,先说明用途,等用户点击再发起,位置也只留必要的部分。
定位代码如果跑在 iframe 里,还要同时满足父页面的 Permissions Policy 和 iframe 的 allow 属性。主页面有授权,不等于每个嵌入的上下文都自动拥有。
第 14.7 题 · 多选题 · 选出所有正确项
定时器与视口:时间和尺寸都不是绝对值
“一秒后提示”“每秒刷新时钟”“窗口变了重算布局”,这类需求分别交给定时器和视口 API。两者给出的数字,都不是硬件级承诺。
定时器只保证“最早”
setTimeout() 安排一次回调,setInterval() 安排重复回调,返回值是任务 id,用 clearTimeout() / clearInterval() 取消:
const timerId = window.setTimeout(() => {
console.log("至少等了约 1000 毫秒");
}, 1000);
cancelButton.addEventListener("click", () => {
window.clearTimeout(timerId);
});
到点只是获得排队资格,主线程要先做完手上的活。
下面这段在浏览器和 Node.js 里结果相同,0 毫秒也不能插队:
setTimeout(() => {
console.log("定时器回调");
}, 0);
console.log("同步结束");同步结束
定时器回调再让主线程忙一会儿,看看“至少”二字的分量:
const start = Date.now();
setTimeout(() => {
const waited = Date.now() - start;
console.log(waited >= 100); // 回调被长任务耽搁
}, 10);
while (Date.now() - start < 100) {
// 空转 100 毫秒,模拟长任务
}true设成 10 毫秒的回调,等了超过 100 毫秒才执行,因为那个循环占着主线程。除了长任务,后台标签页节流、设备负载、浏览器对嵌套定时器的最小延迟,都会让实际延迟更长。setInterval 还会产生漂移。如果下一轮必须等本轮的异步工作完成,递归地安排 setTimeout 比 setInterval 更合适:
let stopped = false;
let round = 0;
async function refreshStatus() {
round += 1;
console.log("第", round, "次刷新");
if (round === 3) stopped = true;
}
async function poll() {
await refreshStatus();
if (!stopped) {
setTimeout(poll, 50);
}
}
poll();第 1 次刷新
第 2 次刷新
第 3 次刷新真实页面里 refreshStatus 往往是一次网络请求,间隔也会是几秒,这里为了让示例瞬间跑完才用了 50 毫秒。组件卸载、功能关闭、任务取消时,别忘了清掉还在等待的定时器。
重复任务同样保存 id 再清理:
const clockId = setInterval(updateClock, 1000);
stopButton.addEventListener("click", () => {
clearInterval(clockId);
});第 14.8 题 · 单选题
屏幕、窗口、可见区域是三回事
页面布局首选 CSS 媒体查询、容器查询和弹性布局。脚本只在必须参与时才监听尺寸,比如按窗口调整 canvas 像素,或者让浮层避开软键盘。
const label = document.querySelector("#viewport-size");
let frameId = null;
function renderViewportSize() {
label.textContent = `${window.innerWidth} × ${window.innerHeight}`;
frameId = null;
}
window.addEventListener("resize", () => {
if (frameId === null) {
frameId = requestAnimationFrame(renderViewportSize);
}
});
renderViewportSize();运行环境:浏览器页面,文档里有 #viewport-size。
resize 拖动窗口时会密集触发,这里借 requestAnimationFrame() 把同一帧内的多次变化合并成一次渲染。移动端想跟踪缩放和软键盘,可以监听 window.visualViewport 的 resize 与 scroll,使用前先判断它存在,老环境可能没有。
下面的观察器可以直接看到定时器的排队、延迟与取消:
第 14.9 题 · 判断题
cookie 与 Web Storage:存数据前先选容器
“存在浏览器里”不是一种行为。cookie、localStorage、sessionStorage 的寿命、范围、是否自动上网,差别很大。

选容器先问三件事:存多久,谁能读,会不会随请求发出去。
一个细节:新页面如果保留了 opener,它的 sessionStorage 初始内容可能从打开者复制而来。复制之后两边各是各的,互不同步。不想要这次复制,可以切断 opener。
Web Storage 只存字符串
Storage 的接口是 setItem()、getItem()、removeItem()、clear()、key() 和 length:
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme")); // dark
localStorage.removeItem("theme");
console.log(localStorage.getItem("theme")); // null对象要先序列化。读和写都放进 try...catch,因为失败来源有两处:JSON 可能已经损坏,存储本身也可能因配额、隐私设置或安全策略而不可用:
const SETTINGS_KEY = "travel-settings";
function saveSettings(settings) {
try {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
return true;
} catch (error) {
console.error("设置保存失败", error);
return false;
}
}
function loadSettings() {
try {
const raw = localStorage.getItem(SETTINGS_KEY);
return raw ? JSON.parse(raw) : { theme: "light" };
} catch (error) {
console.error("设置读取失败", error);
return { theme: "light" };
}
}Web Storage 是同步接口,大量读写会卡住主线程,别拿它存大型数据集。容量规范没有规定固定数字,常见浏览器在几 MB 量级。
同源的另一个页面修改了 localStorage,当前页面会收到 storage 事件,可以据此同步状态:
window.addEventListener("storage", (event) => {
if (event.storageArea !== localStorage) {
return;
}
if (event.key === null) {
// 另一个同源页面调用了 localStorage.clear()
applySettings({ theme: "light" });
return;
}
if (event.key !== SETTINGS_KEY) {
return;
}
if (event.newValue === null) {
// 目标键被 removeItem() 删除
applySettings({ theme: "light" });
return;
}
try {
applySettings(JSON.parse(event.newValue));
} catch {
console.warn("忽略了无法解析的设置数据");
}
});开头先核对 event.storageArea,是为了不把 sessionStorage 里同名键的变化误当成持久设置。clear() 触发的事件里 key 与 newValue 都是 null;removeItem() 触发的事件里 key 仍是被删的键名,newValue 为 null。另外,执行写入的这个页面自己通常收不到这次事件,所以写成功后要直接更新自己的界面。
运行环境:浏览器页面;示例假定页面里另有 applySettings 函数。
第 14.10 题 · 多选题 · 选出所有正确项
document.cookie:每次赋值只写一条
读取 document.cookie 得到分号分隔的一长串;给它赋值却不是替换整串,只是在当前作用域设置或更新其中一条:
document.cookie =
`theme=${encodeURIComponent("dark")}; Max-Age=86400; Path=/; SameSite=Lax; Secure`;读取要自己拆分:
function getCookie(name) {
const prefix = `${encodeURIComponent(name)}=`;
for (const part of document.cookie.split(";")) {
const cookie = part.trim();
if (cookie.startsWith(prefix)) {
return decodeURIComponent(cookie.slice(prefix.length));
}
}
return null;
}
console.log(getCookie("theme"));运行环境:浏览器页面。Secure 的 cookie 在普通 HTTP 页面上会被拒绝,localhost 的处理各浏览器不完全一致,调试时拿不准就看开发者工具的 Application 面板。
几个常用属性:
Max-Age或Expires决定过期时间;Path、Domain决定发送范围,Domain能收窄就收窄;Secure让 cookie 只走安全连接;SameSite限制跨站请求是否携带,能降低一部分跨站请求伪造的风险;HttpOnly禁止页面脚本读取,只能由服务端在响应头里设置。
删除 cookie 的办法,是用相同的名称、Path、Domain 再写一次,把 Max-Age 设为 0 或把过期时间设到过去。
第 14.11 题 · 单选题
本地存储不是保险柜
同源脚本能读到该源下的 localStorage、sessionStorage 和所有非 HttpOnly 的 cookie。页面一旦有 XSS 漏洞,注入的脚本拥有同样的读取权限。落到做法上:
- 密码、身份证号、长期访问令牌这类高价值秘密,不放进去;
- 会话 cookie 由服务端设成
HttpOnly、Secure,并配上合适的SameSite; - 从存储里读出的数据照样是不可信输入,显示时用
textContent,不要拼进innerHTML; - 只存功能需要的数据,给用户清除入口,遵守所在地区的隐私与同意要求;
- 别以为数据永远在:用户清站点数据、无痕模式、浏览器策略都可能让它消失。
localStorage 解决的是“持久保存字符串”,不是“安全保存秘密”。安全要靠最小化数据、服务端会话设计、输出转义和完善的 XSS 防护一起撑起来。
第 14.12 题 · 判断题
File 与 FileReader:只读用户亲手交出的文件
网页不能随意浏览用户的硬盘。能处理的只有用户通过 <input type="file"> 或拖放明确交给页面的 File 对象。这条边界让本地预览成为可能,也让网页没法悄悄扫描文件系统。
先看元数据
<label>
导入行程 JSON
<input id="file-input" type="file" accept="application/json,.json" />
</label>
<pre id="file-output">尚未选择文件</pre>用户选好后,input.files 是一个 FileList,每个 File 带有 name、size、type、lastModified:
const input = document.querySelector("#file-input");
input.addEventListener("change", () => {
const file = input.files?.[0];
if (!file) {
return;
}
console.log({
name: file.name,
size: file.size,
type: file.type,
lastModified: file.lastModified
});
});accept 只是给文件选择器的提示,用户照样能选别的文件;MIME type 也可能为空或不准。前端检查扩展名、类型和大小,是为了让用户早点看到提示。文件如果还要上传,服务端必须按真实内容重新验证。
第 14.13 题 · 单选题
用 FileReader 异步读取
读取文本要经过 FileReader。下面的示例限制大小、读取文本、解析 JSON,并用 textContent 显示结果。它还处理了一个常见的竞态:用户连续选了两个文件,先选的那个读得慢,后到的回调就不该覆盖当前提示。
const input = document.querySelector("#file-input");
const output = document.querySelector("#file-output");
let activeReader = null;
input.addEventListener("change", () => {
const previousReader = activeReader;
activeReader = null;
previousReader?.abort();
const file = input.files?.[0];
if (!file) {
output.textContent = "没有选择文件。";
return;
}
if (file.size > 100 * 1024) {
output.textContent = "文件不能超过 100 KB。";
input.value = "";
return;
}
const reader = new FileReader();
activeReader = reader;
output.textContent = "正在读取…";
reader.addEventListener("load", () => {
if (activeReader !== reader) return;
try {
const data = JSON.parse(String(reader.result));
output.textContent = JSON.stringify(data, null, 2);
} catch {
output.textContent = "文件不是有效的 JSON。";
}
});
reader.addEventListener("error", () => {
if (activeReader !== reader) return;
output.textContent = `读取失败:${reader.error?.message ?? "未知错误"}`;
});
reader.addEventListener("abort", () => {
if (activeReader !== reader) return;
output.textContent = "已取消读取。";
});
reader.addEventListener("loadend", () => {
if (activeReader === reader) {
activeReader = null;
}
});
reader.readAsText(file, "utf-8");
});运行环境:浏览器页面,文档里有前面那段 HTML。
处理顺序是:新选择一到,先把旧任务摘掉再 abort(),哪怕新选择为空或超限也一样;各个回调开头再确认自己仍是当前任务。读取结果取决于调用的方法:
读取是异步的,result 要等 load 之后才能用。图片预览可以走 readAsDataURL():
function previewImage(file, imageElement) {
if (!file.type.startsWith("image/")) {
throw new Error("请选择图片文件");
}
const reader = new FileReader();
reader.addEventListener("load", () => {
imageElement.src = String(reader.result);
imageElement.alt = file.name;
});
reader.readAsDataURL(file);
}图片大时,只为预览的话 URL.createObjectURL(file) 通常比 data URL 省内存,不用时记得 URL.revokeObjectURL(url)。无论哪种做法,文件名和文件内容都不要直接拼进 innerHTML。
第 14.14 题 · 多选题 · 选出所有正确项
iframe、window.open 与 postMessage:跨上下文通信
顶层页面、iframe、新窗口各有一个 window。它们能拿到彼此的引用,但能不能直接读对方的 DOM 和变量,首先取决于同源策略(same-origin policy)。

协议、主机名、端口三者都相同才叫同源,路径不同不影响判断。
iframe 与窗口引用
同源的 iframe,父页面可以通过 contentWindow 访问它的文档:
const frame = document.querySelector("#preview-frame");
frame.addEventListener("load", () => {
// 只有 frame 内容与父页面同源才允许这样读
console.log(frame.contentWindow.document.title);
});在 iframe 内部,window.parent 指向父上下文,window.top 指向最顶层。跨源时浏览器会拦下大部分直接读取。sandbox 属性还能进一步限制 iframe 的脚本、表单、弹窗和源身份:只写真正需要的令牌,别一口气全放开。
第 14.15 题 · 判断题
window.open 可能得到 null
浏览器一般只允许在用户手势期间打开窗口:
openButton.addEventListener("click", () => {
const child = window.open(
"/help",
"help-window",
"popup,width=720,height=600"
);
if (!child) {
showMessage("窗口被浏览器拦截,请允许弹窗后重试。");
}
});打开不受信任的外部页面,要切断 opener,否则新页面能通过 window.opener 回头操作你的页面:
<a
href="https://example.org"
target="_blank"
rel="noopener noreferrer"
>
打开外部页面
</a>脚本里可以写 window.open(url, "_blank", "noopener")。注意规范规定带 noopener 时返回值就是 null,所以此时既拿不到窗口引用,也不能把这个 null 当成“弹窗被拦截”的证据。
第 14.16 题 · 单选题
postMessage:明确的消息通道
跨源页面确实要协作时,发送方必须写明目标 origin:
const frame = document.querySelector("#map-frame");
const mapOrigin = "https://map.example";
frame.addEventListener("load", () => {
frame.contentWindow.postMessage(
{
type: "map:center",
payload: { latitude: 31.2304, longitude: 121.4737 }
},
mapOrigin
);
});接收方至少验三样:event.origin、event.source、数据结构。
const allowedParentOrigin = "https://learn.example";
window.addEventListener("message", (event) => {
if (event.origin !== allowedParentOrigin) {
return;
}
if (event.source !== window.parent) {
return;
}
const message = event.data;
const latitude = message?.payload?.latitude;
const longitude = message?.payload?.longitude;
if (
message?.type !== "map:center" ||
!Number.isFinite(latitude) ||
!Number.isFinite(longitude) ||
latitude < -90 ||
latitude > 90 ||
longitude < -180 ||
longitude > 180
) {
return;
}
centerMap({ latitude, longitude });
});运行环境:前一段在父页面(https://learn.example),后一段在 https://map.example 的页面里,需要两个不同源的页面配合,单机直接打开文件无法复现。
发送端的 targetOrigin 一般要写具体值。只有接收方 origin 确实无法预知时才不得不用 "*",那就别在消息里放任何敏感内容。收到的 event.data 始终是外部输入,不能直接写进 innerHTML,更不能当命令执行。
下面的演示可以试着伪造来源、改坐标,看哪一道检查把消息拦下。
第 14.17 题 · 多选题 · 选出所有正确项
综合实践:浏览器能力面板
把地址、历史、存储、文件、定位和定时器装进一个页面。新建 index.html 和 app.js,放在同一个目录,用本地开发服务器打开。
第一步:页面骨架
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>浏览器能力面板</title>
<style>
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
body { max-width: 760px; margin: 0 auto; padding: 24px; }
section { margin-block: 28px; }
button, select, input { margin: 4px; }
pre { overflow: auto; padding: 12px; }
</style>
</head>
<body>
<h1>浏览器能力面板</h1>
<section>
<h2>路由与偏好</h2>
<button type="button" data-view="overview">概览</button>
<button type="button" data-view="files">文件</button>
<button type="button" data-view="location">定位</button>
<p id="route-output"></p>
<label>
主题
<select id="theme">
<option value="light">浅色</option>
<option value="dark">深色</option>
</select>
</label>
</section>
<section>
<h2>导入 JSON</h2>
<input id="file-input" type="file" accept="application/json,.json" />
<pre id="file-output">尚未读取文件</pre>
</section>
<section>
<h2>定位与提醒</h2>
<button id="locate" type="button">请求当前位置</button>
<p id="position">尚未请求定位</p>
<button id="start-timer" type="button">3 秒后提醒</button>
<button id="cancel-timer" type="button">取消提醒</button>
<p id="timer-output">没有待执行提醒</p>
</section>
<script src="./app.js"></script>
</body>
</html>第二步:app.js
文件读取的部分沿用前面的取消旧任务思路,这里写得紧凑一些。
const $ = (selector) => document.querySelector(selector);
const routeOutput = $("#route-output");
const themeSelect = $("#theme");
const fileInput = $("#file-input");
const fileOutput = $("#file-output");
const positionOutput = $("#position");
const timerOutput = $("#timer-output");
const THEME_KEY = "capability-panel:theme";
let timerId = null;
let activeReader = null;
// 路由:地址是唯一的真相,渲染都从地址读
function renderRoute() {
const view = new URL(location.href).searchParams.get("view") ?? "overview";
routeOutput.textContent = `当前视图:${view}`;
}
document.querySelectorAll("[data-view]").forEach((button) => {
button.addEventListener("click", () => {
const nextUrl = new URL(location.href);
nextUrl.searchParams.set("view", button.dataset.view);
history.pushState({ view: button.dataset.view }, "", nextUrl);
renderRoute();
});
});
window.addEventListener("popstate", renderRoute);
renderRoute();
// 主题:存储可能不可用,失败时降级而不是崩溃
function applyTheme(theme) {
document.documentElement.style.colorScheme = theme;
}
try {
const saved = localStorage.getItem(THEME_KEY);
if (saved === "light" || saved === "dark") {
themeSelect.value = saved;
applyTheme(saved);
}
} catch {
themeSelect.disabled = true;
}
themeSelect.addEventListener("change", () => {
applyTheme(themeSelect.value);
try {
localStorage.setItem(THEME_KEY, themeSelect.value);
} catch {
alert("浏览器未允许保存主题。");
}
});
// 文件:限制大小,新选择取消旧读取
fileInput.addEventListener("change", () => {
const previous = activeReader;
activeReader = null;
previous?.abort();
const file = fileInput.files?.[0];
if (!file) {
fileOutput.textContent = "没有选择文件。";
return;
}
if (file.size > 100 * 1024) {
fileOutput.textContent = "文件不能超过 100 KB。";
fileInput.value = "";
return;
}
const reader = new FileReader();
activeReader = reader;
fileOutput.textContent = "正在读取…";
reader.addEventListener("load", () => {
if (activeReader !== reader) return;
try {
const data = JSON.parse(String(reader.result));
fileOutput.textContent = JSON.stringify(data, null, 2);
} catch {
fileOutput.textContent = "这不是有效的 JSON 文件。";
}
});
reader.addEventListener("error", () => {
if (activeReader === reader) fileOutput.textContent = "文件读取失败。";
});
reader.addEventListener("abort", () => {
if (activeReader === reader) fileOutput.textContent = "已取消读取。";
});
reader.addEventListener("loadend", () => {
if (activeReader === reader) activeReader = null;
});
reader.readAsText(file, "utf-8");
});
// 定位:成功、拒绝、超时,三条路都要结束“正在请求”
$("#locate").addEventListener("click", () => {
if (!("geolocation" in navigator)) {
positionOutput.textContent = "当前环境不支持定位。";
return;
}
positionOutput.textContent = "正在请求位置…";
navigator.geolocation.getCurrentPosition(
({ coords }) => {
positionOutput.textContent =
`${coords.latitude.toFixed(5)}, ${coords.longitude.toFixed(5)}` +
`(精度约 ${Math.round(coords.accuracy)} 米)`;
},
(error) => {
positionOutput.textContent = `定位失败,错误码:${error.code}`;
},
{ timeout: 8000, maximumAge: 60_000 }
);
});
// 提醒:重复点击先清掉旧的
$("#start-timer").addEventListener("click", () => {
if (timerId !== null) clearTimeout(timerId);
timerOutput.textContent = "提醒已安排。";
timerId = setTimeout(() => {
timerOutput.textContent = "该休息一下了。";
timerId = null;
}, 3000);
});
$("#cancel-timer").addEventListener("click", () => {
if (timerId === null) return;
clearTimeout(timerId);
timerId = null;
timerOutput.textContent = "提醒已取消。";
});第三步:验收
准备一个小于 100 KB 的测试文件:
{
"city": "上海",
"days": 3,
"notes": ["带伞", "提前订票"]
}逐项检查:
- 点三个视图按钮,地址栏的
view参数与页面文字同步变化; - 连点几次后用浏览器后退、前进,文字跟着当前 URL 走;
- 切换主题再刷新,允许存储时主题保持;
- 导入有效 JSON 能格式化显示,超大或无效文件给出错误;
- 点定位后,无论授权、拒绝还是失败,“正在请求”都会消失;
- 启动提醒等三秒能看到消息,提前取消则不会出现;
- 控制台没有未处理的异常,窄屏下仍然可以操作。
定位请在 HTTPS 或 localhost 上测试。经纬度、精度、授权弹窗和等待时间都由设备与浏览器决定,别写成固定结果。
本章自测
第 14.18 题 · 单选题
第 14.19 题 · 多选题 · 选出所有正确项
第 14.20 题 · 填空题
第 14.21 题 · 判断题
第 14.22 题 · 单选题
第 14.23 题 · 多选题 · 选出所有正确项
总结
window是当前浏览上下文的全局入口,document负责 DOM,其他宿主环境不一定提供window。- 用
URL与URLSearchParams拆解地址;跳转前先验证不可信的目标。 pushState()新增历史项,replaceState()替换当前项,两者都不会自动渲染 DOM。- 定时器延迟是最早排队时间,不是精确时刻;任务结束要及时清理。
- 响应式布局优先交给 CSS,脚本只在必要时读取布局视口或视觉视口。
- Web Storage 只存字符串且不是保险柜;cookie 的网络行为与安全属性要一并考虑。
FileReader只能读页面已拿到的文件,结果在事件回调里处理,上传内容仍需服务端验证。- 定位要由明确的用户操作触发,处理好权限、超时、精度与隐私。
- iframe 与新窗口受同源策略约束,
postMessage()必须限定目标 origin,并校验收到的 origin、窗口与数据结构。