Chrome扩展command命令传递到content script实现热键触发功能问题
修复方案
你遇到的问题核心有三点:
- 热键监听放在popup.js中会受popup生命周期限制,只有popup处于打开状态时监听才有效,关闭后监听直接销毁,无法正常响应热键
- 缺少从热键监听侧到content script的消息发送逻辑,以及content script侧的消息接收逻辑
- manifest.json存在两处配置错误,会导致content script注入失败、权限申请异常
以下是分步修复代码:
1. 修正manifest.json配置
{ "manifest_version": 2, "name": "Ccghjj", "description": "hdjdjdjsjs", "version": "1.0", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, // 修正错误的storage权限配置 "permissions": ["tabs", "storage", "activeTab"], "content_scripts": [ { // 修正错误的页面匹配规则 "matches": ["<all_urls>"], "css": ["style.css"], "js": ["jquery.js", "main.js"] } ], // 新增后台脚本配置,用于持久化监听热键 "background": { "scripts": ["background.js"], "persistent": false }, "content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'", "web_accessible_resources": ["toolbar.html", "style.css"], "commands": { "show_deals": { "suggested_key": { "default": "Ctrl+Shift+K" }, "description": "Highlight Deals" } } }
2. 新增background.js(热键持久化监听)
后台脚本不会随popup关闭销毁,可全局监听热键事件:
chrome.commands.onCommand.addListener((command) => { if (command !== 'show_deals') return // 查询当前激活的标签页,发送触发指令 chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.tabs.sendMessage(tabs[0].id, { action: 'run_deals' }) }) });
3. 移除popup.js中的重复热键监听逻辑
原popup.js中的chrome.commands.onCommand监听段可直接删除,避免重复监听。
4. 给main.js添加消息接收逻辑
content script侧监听后台发来的指令,触发对应的deals函数:
// 原有deals函数 async function deals() { // 原有业务逻辑 } // 新增消息监听 chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === 'run_deals') { deals() } })
生效方式
修改完成后在扩展管理页面重新加载扩展即可,热键全局生效,无需保持popup打开状态即可触发。
内容的提问来源于stack exchange,提问作者exec85
相关产品推荐
相关产品推荐

