【发布时间】:2021-12-11 07:42:42
【问题描述】:
我想在我的内容脚本中实现一个触发函数的热键。 内容脚本 (main.js) 在我的 popup.js 文件中的页面 laod 上执行。
我已将命令添加到我的 manifest.json 中,当我将 onCommand 侦听器添加到我的 popup.js 时,我可以控制台记录当我按下热键 (Ctrl+Shift+K) 时触发它
但是我无法将它传递给我的内容脚本。
manifest.json
{
"manifest_version": 2,
"name": "Ccghjj",
"description": "hdjdjdjsjs",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "*storage", "activeTab"],
"content_scripts": [
{
"matches": ["*://"],
"css": ["style.css"],
"js": ["jquery.js", "main.js"]
}
],
"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"
}
}
}
popup.js
function registerButtonAction(tabId, button, action) {
// clicking button will send a message to
// content script in the same tab as the popup
button.addEventListener('click', () => chrome.tabs.sendMessage(tabId, { [action]: true }));
}
function setupButtons(tabId) {
// add click actions to each 3 buttons
registerButtonAction(tabId, document.getElementById('start-btn'), 'startSearch');
registerButtonAction(tabId, document.getElementById('deals-btn'), 'startDeals');
registerButtonAction(tabId, document.getElementById('stop-btn'), 'stopSearch');
}
function injectStartSearchScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// Injects JavaScript code into a page
// chrome.tabs.executeScript(tabs[0].id, { file: 'main.js' });
// add click handlers for buttons
setupButtons(tabs[0].id);
});
}
injectStartSearchScript();
// hotkey command listener
chrome.commands.onCommand.addListener((show_deals) => {
console.log(`Command "${show_deals}" triggered`);
// how can I get to main.js to call deals()
});
main.js(内容脚本)
async function deals() {
// should be fired when I press my hotkey Ctrl+Shift+K
【问题讨论】:
-
您的清单显示命令键为
K,而您写的内容是D。 -
抱歉,已更正-它是
K -
我对chrome扩展不是特别熟悉;所以,这更像是一个一般性的建议。在命令侦听器中,您必须根据传递给侦听器的命令值调用该函数。你只有一个命令
show_deals所以没关系,除非添加另一个。如果侦听器在后台脚本中,而函数在内容脚本中,请使用您的runtime port or one-off messaging 通知内容脚本调用它。 -
它在概念上似乎与在内容脚本本身中为
keydown事件注册一个侦听器并调用所需的函数没有太大不同。您必须测试检测到哪个命令并调用该函数。在这个 chrome 命令设置中,命令侦听器和函数似乎是分开的,前者在 BS 中,后者在 CS 中;但其余的逻辑看起来是一样的。
标签: javascript html google-chrome-extension sendmessage content-script