Chrome扩展如何为整个窗口注册鼠标点击事件监听器?
我尝试在Chrome扩展中为整个浏览器窗口注册鼠标点击事件监听器,目标是打开扩展弹窗后,点击任意标签页都能触发事件(打开新的谷歌标签页)。但目前仅在扩展所在标签页点击时生效,其他标签页点击无响应。
注意:点击扩展弹窗本身时,点击事件也不会触发。
测试场景:点击弹窗的「Initialize Navigation Capture」按钮,会在新标签页加载另一个HTML页面。在这个新页面中,鼠标点击能正常触发打开谷歌标签页,但仅限该页面生效。
现有代码
manifest.json
{ "manifest_version": 3, "name": "Traffic Capturer", "version": "1.0.0", "author": "Lucas Pletsch", "action": { "default_title": "Traffic Capturer", "default_icon": "icone.jpg", "default_popup": "index.html" }, "description": "Reads the navigation data", "content_scrips": [ { "matches": ["https://*/"], "js": ["./js/eventsCapturer.js"] } ], "host_permissions": ["https://*/"], "permissions": [ "webNavigation", "scripting", "tabs" ] }
./js/eventsCapturer.js
function addClickListener() { document.addEventListener('click', () => { console.log('Clicou em alguma parte da tela') chrome.tabs.create({url: "http://www.google.com"}, ()=>console.log("Janela aberta")) }) }
弹窗HTML(index.html)
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>Navigation Capturer</title> <link rel='stylesheet' type='text/css' media='screen' href='main.css'> </head> <body> <button id="initializer">Initialize Navigation Capture</button> </body> <script src='./js/capturerInitializer.js'></script> </html>
./js/capturerInitializer.js
var timer const initializerButton = document.querySelector('#initializer') initializerButton.addEventListener('click', function () { initializeCapturerInNewTab() }) async function initializeCapturerInNewTab() { const tab = chrome.tabs.create({ url: '../html_components/controls.html' }) return tab }
新标签页HTML(controls.html)
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>Navigation Capturer</title> <link rel='stylesheet' type='text/css' media='screen' href='main.css'> </head> <body> <span>hi</span> </body> </html>
问题分析与修复方案
Manifest拼写错误
content_scrips存在拼写错误,正确应为content_scripts,这会导致Content Script无法被正确注入到匹配页面。Content Script匹配规则限制
当前matches: ["https://*/"]仅匹配HTTPS站点的根路径(如https://example.com/),无法覆盖子路径页面(如https://example.com/article)。需修改为:"matches": ["https://*/*"]Content Script未执行函数
eventsCapturer.js中仅定义了addClickListener函数,但未调用。需在脚本末尾添加:addClickListener();已打开标签页未注入脚本
默认的content_scripts仅在页面加载时注入,已打开的标签页不会自动生效。需在初始化按钮点击时,主动向所有已打开的匹配标签页注入脚本,修改capturerInitializer.js:async function initializeCapturerInNewTab() { // 向所有已打开的HTTPS标签页注入脚本 const tabs = await chrome.tabs.query({url: "https://*/*"}); for (const tab of tabs) { await chrome.scripting.executeScript({ target: {tabId: tab.id}, files: ["./js/eventsCapturer.js"] }); } // 打开新标签页 const tab = chrome.tabs.create({ url: '../html_components/controls.html' }); return tab; }弹窗点击事件捕获
扩展弹窗属于独立的隔离上下文,Content Script无法捕获其点击事件。若需要捕获弹窗内的点击,需在弹窗脚本(capturerInitializer.js)中直接添加监听器:// 在capturerInitializer.js中添加 document.addEventListener('click', () => { console.log('弹窗被点击'); chrome.tabs.create({url: "http://www.google.com"}); });
内容的提问来源于stack exchange,提问作者Lucas

