Manifest V3下content_scripts如何检测自定义快捷键是否已设置?
解决Manifest V3中Content-Script判断自定义快捷键状态的问题
针对你遇到的「Content-Script需要判断用户是否自定义了快捷键,避免重复监听ESC键」的问题,这里提供两个实用方案:
方案一:通过Background实时同步快捷键状态
核心思路是让Background脚本维护当前快捷键的配置状态,Content-Script在初始化或需要时主动请求状态,以此决定是否启用ESC键监听。
实现步骤
Background.js 代码
// 标记当前是否使用默认ESC快捷键 let isDefaultEsc = true; // 扩展启动/安装时更新状态 chrome.runtime.onStartup.addListener(updateShortcutStatus); chrome.runtime.onInstalled.addListener(updateShortcutStatus); // 更新快捷键状态 async function updateShortcutStatus() { const commands = await chrome.commands.getAll(); // 替换成你在manifest中定义的命令名 const targetCmd = commands.find(cmd => cmd.name === "your-custom-command"); isDefaultEsc = targetCmd?.shortcut === "Escape"; } // 响应Content-Script的状态请求 chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { if (msg.type === "get-shortcut-status") { sendResponse({ isDefaultEsc }); } return true; // 异步响应需返回true });Content-Script 代码
let shouldListenEsc = true; const escHandler = (e) => { if (e.key === "Escape") { // 你的原有ESC键操作逻辑 } }; // 初始化时获取状态并设置监听 chrome.runtime.sendMessage({ type: "get-shortcut-status" }, (res) => { if (res) { shouldListenEsc = res.isDefaultEsc; toggleEscListener(shouldListenEsc); } }); // 切换ESC键监听 function toggleEscListener(enable) { if (enable) { document.addEventListener("keydown", escHandler); } else { document.removeEventListener("keydown", escHandler); } } // 可选:定期同步状态(应对用户修改快捷键后未重启扩展的情况) setInterval(async () => { const res = await chrome.runtime.sendMessage({ type: "get-shortcut-status" }); if (res && shouldListenEsc !== res.isDefaultEsc) { shouldListenEsc = res.isDefaultEsc; toggleEscListener(shouldListenEsc); } }, 60000);
方案二:利用命令触发标记判断(更简洁)
核心思路是利用chrome.commands.onCommand的优先级——当用户设置了自定义快捷键,该事件会优先触发,此时让Background给当前标签页的Content-Script发送一个「已处理」标记,Content-Script收到标记后跳过ESC键的处理;若未收到标记,说明仍使用默认ESC键,继续执行原有逻辑。
实现步骤
Background.js 代码
chrome.commands.onCommand.addListener((command) => { if (command === "your-custom-command") { // 执行你的命令逻辑 // 通知当前活跃标签页的Content-Script:快捷键已被处理 chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { if (tabs[0]) { chrome.tabs.sendMessage(tabs[0].id, { type: "shortcut-handled" }); } }); } });Content-Script 代码
let shortcutHandled = false; // 监听Background的标记消息 chrome.runtime.onMessage.addListener((msg) => { if (msg.type === "shortcut-handled") { shortcutHandled = true; } }); document.addEventListener("keydown", (e) => { if (e.key === "Escape") { if (shortcutHandled) { shortcutHandled = false; // 重置标记,避免影响下一次 return; } // 你的原有ESC键操作逻辑 } });
这个方案无需维护状态,自动适配用户删除快捷键后恢复ESC键的场景,且不需要额外UI,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Craig Francis
相关产品推荐
相关产品推荐

