Chrome扩展开发:content script匹配网页标题关键词后如何通过消息传递触发通知
Chrome扩展Content Script触发Background调用Notification API实现方案
*核心原理:Content Script与Background Service Worker处于完全隔离的脚本执行环境,二者通过chrome.runtime系列API完成跨环境消息通信,Content Script仅负责检测标题关键词,命中后发送消息通知Background,由Background完成Notification API调用。
1. 前置Manifest权限配置
首先需要在manifest.json中声明必要权限、注册Content Script与Background入口,示例配置:
{ "manifest_version": 3, "name": "标题关键词通知扩展", "version": "1.0", "permissions": ["notifications"], "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ], "background": { "service_worker": "background.js" }, "icons": { "128": "icons/icon128.png" } }
matches字段可按需调整为指定站点域名,无需匹配全站点icons字段需提前在扩展目录下放置对应尺寸的图标文件,避免通知加载异常
2. Content Script 逻辑实现(content.js)
Content Script仅负责当前页面标题检测、关键词命中判断,命中后发送消息给Background,同时适配SPA单页应用的标题动态变化场景,代码示例:
// 自定义待匹配的关键词列表 const TARGET_KEYWORDS = ["关键词1", "关键词2"]; // 已通知过的标题缓存,用于去重避免重复触发 let lastNotifiedTitle = ""; function checkTitleMatch() { const currentTitle = document.title; // 已通知过的标题直接跳过 if (currentTitle === lastNotifiedTitle) return; // 检测是否命中任意关键词 const isMatched = TARGET_KEYWORDS.some(keyword => currentTitle.includes(keyword)); if (isMatched) { lastNotifiedTitle = currentTitle; // 向Background发送命中消息,携带标题参数 chrome.runtime.sendMessage({ type: "TITLE_KEYWORD_HIT", payload: { title: currentTitle } }); } } // 页面初次加载完成时执行一次检测 window.addEventListener("load", checkTitleMatch); // 监听DOM中title节点的变化,适配SPA无刷新改标题的场景 const titleObserver = new MutationObserver(checkTitleMatch); titleObserver.observe(document.querySelector("title"), { subtree: true, characterData: true, childList: true });
3. Background 脚本逻辑实现(background.js)
Background负责接收Content Script发来的命中消息,调用Notification API弹出通知,支持两种通知实现方案,按需选择即可:
// 监听Content Script的消息推送 chrome.runtime.onMessage.addListener((request) => { if (request.type === "TITLE_KEYWORD_HIT") { const matchedTitle = request.payload.title; // 方案1:使用Chrome扩展原生Notifications API(兼容性更好,支持扩展专属配置) chrome.notifications.create({ type: "basic", iconUrl: "icons/icon128.png", title: "检测到匹配关键词", message: `当前页面标题:${matchedTitle}` }); // 方案2:使用Web标准Notification API(和普通网页调用的API完全一致) // new Notification("检测到匹配关键词", { // body: `当前页面标题:${matchedTitle}`, // icon: "icons/icon128.png" // }); } });
*注意:Web标准Notification API在Background Service Worker中调用时,依赖notifications权限授权,只要在Manifest中声明该权限即可自动获得授权,无需额外申请。
常见问题排查
- 通知未弹出:先检查Manifest中是否遗漏
notifications权限、图标路径是否和实际文件路径匹配 - 单页应用切换页面后未触发检测:确认是否添加了
MutationObserver监听title节点变化,不要仅依赖页面load事件 - 同一标题重复弹出通知:检查Content Script中的标题去重逻辑,也可在Background端增加短时间内的相同内容通知拦截规则
内容的提问来源于stack exchange,提问作者Mate
相关产品推荐
相关产品推荐

