MV3 content script 跨域 iframe 通信兜底
背景与问题
一个 MV3 扩展需要读取页面内 iframe 中的用户选区。主 frame 的 content script 能正常运行,但 iframe.contentDocument 返回 null,postMessage 发出去的消息也像进了黑洞。问题不是“postMessage 写错了”,而是 iframe 的 frame 树、权限和 sandbox 边界共同决定了一条消息能不能抵达对端。
第一个边界是注入范围。主 frame 的 content script 默认不会进入 iframe。只写 all_frames: true 还不够,about:blank、srcdoc 和 blob: frame 没有可匹配的 URL,需要 match_origin_as_fallback: true 才能按创建者的 origin 命中。如果 iframe 带 sandbox 且不含 allow-same-origin,Chrome 会直接阻止 content script 注入,这是强制安全限制,没有任何 manifest 配置可以绕过。-
2
-
13
第二个边界是通信方向。postMessage 本身是单向广播,没有请求-回复语义,也没有超时。发出去之后如果对端不存在、未就绪或注入失败,调用方会永远等待。更麻烦的是,当页面存在多个 iframe 或嵌套 iframe 时,多个通道的消息可能互相串扰。
方案设计
兜底不能只靠一种机制,要按 frame 类型分层:
第一层是注入侧。在 manifest 中同时开启 all_frames 和 match_origin_as_fallback,让常规跨域 iframe 和 about:blank/srcdoc frame 都有机会被覆盖:
json
复制
下载
{
"manifest_version": 3,
"host_permissions": ["https://app.example.com/*"],
"content_scripts": [{
"matches": ["https://app.example.com/*"],
"js": ["content/frame-probe.js"],
"all_frames": true,
"match_origin_as_fallback": true,
"run_at": "document_start"
}]
}
第二层是通信侧。用 MessageChannel 把单向 postMessage 包装成带超时的请求-回复。关键不是 postMessage 本身,而是把 port2 转移给对端,请求方只监听 port1,并在超时后主动关闭端口,避免泄漏。
第三层是职责切分。子 frame 注入后不要跑完整业务逻辑,先判断自己是不是顶层:不是就立刻早退,只保留最小的上报能力。否则同一个标签页会出现多套 documentId,Service Worker 侧按 documentId 索引的端口会被子 frame 顶掉,主 frame 反而收不到回包。-
5
第四层是 sandbox 降级。对于 sandbox 不含 allow-same-origin 的 iframe,content script 注入不了,唯一可行的兜底是父页面通过 postMessage 触发 iframe 内部预置的钩子,或改用扩展自己的页面作为桥接帧,而不是继续和 content script 死磕。
关键代码或配置示例
带超时的跨域请求-回复实现:
javascript
复制
下载
function requestFrame(targetWindow, payload, timeoutMs = 3000) {
const channel = new MessageChannel();
const main = new Promise((resolve, reject) => {
channel.port1.onmessage = ({ data }) => {
channel.port1.close();
data instanceof Error ? reject(data) : resolve(data);
};
targetWindow.postMessage(payload, "*", [channel.port2]);
});
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("FRAME_TIMEOUT")), timeoutMs)
);
return Promise.race([main, timeout]).finally(() => channel.port1.close());
}
// 子 frame 侧:先早退,再装探测器
if (window.top !== window) {
window.addEventListener("message", (event) => {
if (!event.ports[0]) return;
event.ports[0].postMessage({ type: "FRAME_READY" });
});
} else {
bootFullController();
}
超时后 finally 中的 port1.close() 是必须的。不加这一行,超时请求的端口会一直挂着,积累多了之后 Service Worker 侧的 onmessage 回调会越来越慢。
踩坑与验证
第一个坑是 match_origin_as_fallback 导致重复注入。Chrome 在某些情况下会把已经用 URL 匹配到的 frame 再按 fallback origin 匹配一次,脚本执行两次,探测器被装了两遍,消息回了两份。验证时在 content script 顶部打印 window.location.href 和 performance.timeOrigin,如果同一个 frame 出现两条完全相同的记录,就是重复注入。
第二个坑是 runtime.sendMessage 到不了 content script。子 frame 的 content script 能用 chrome.runtime.sendMessage 发给 Service Worker,但 Service Worker 不能用 runtime.sendMessage 主动推给某个 content script;要定位到具体 frame,必须用 chrome.tabs.sendMessage(tabId, msg, { frameId })。一开始用 runtime.sendMessage 做下行,表现是“主 frame 能收,子 frame 永远收不到”,换成 tabs.sendMessage 并显式传 frameId 后才稳定。
第三个坑是 sandbox 判断缺失。上线前用一个带 sandbox="allow-scripts" 的测试 iframe 跑一遍,确认扩展在该 frame 中没有任何注入成功迹象,然后把该场景纳入降级分支的监控指标。没有这个指标,线上只能看到“用户说时好时坏”,无法定位是哪些页面走了 sandbox 路径。
小结
content script 与跨域 iframe 的通信兜底,本质上是承认浏览器给出的边界不可逾越,然后在边界内把能控制的环节做到可观测、可超时、可降级。manifest 的 all_frames 加 match_origin_as_fallback 解决“进得去”,MessageChannel 加超时解决“等得到”,子 frame 早退解决“不打架”,sandbox 降级解决“认了但不沉默”。四个环节里少任何一个,线上表现都会变成难以复现的间歇性失败。
- 点赞
- 收藏
- 关注作者
评论(0)