Chrome 扩展中的触发器快捷方式
Trigger shortcut in a Chrome extension
我正在构建一个 Chrome 扩展,并将命令 _execute_browser_action
分配给 Alt+J。我想在 background.js 中模拟这个,它使用
监听所有命令
chrome.commands.onCommand.addListener(function(command) { /* ... */ });
我希望通过不同的命令快捷方式调用 _execute_browser_action
,比如 Cmd+Shift+K
在我的 manifest.json 中,我声明了以下内容:
"commands": {
"_execute_browser_action": {
"suggested_key": {
"mac": "Alt+J",
"linux": "Ctrl+Shift+J"
}
},
"asdf" : {
"suggested_key": {
"default": "Ctrl+Shift+K",
"mac": "Command+Shift+K"
},
"description": "asdf"
}
}
这是我的 background.js:
chrome.commands.onCommand.addListener(function(command) {
console.log('onCommand event received for message: ', command);
if (command === "asdf") {
alert("asdf");
var keyPress = jQuery.Event("keypress");
keyPress.altKey = true;
keyPress.ctrlKey = false;
keyPress.which = 74;
//how do I trigger this?
}
});
我想知道如何触发它以便我的 popup.html 打开。
您无法自行触发键盘快捷键。
把它想象成事件的时间轴:
- 一个硬件事件发生,并被OS翻译成输入事件。
- 如果它是 Chrome 注册的全局快捷方式,或者如果 Chrome 获得焦点,则 OS 将事件分派给 Chrome。
- Chrome 检查它是否是已注册的快捷方式。如果是,则触发相应的事件。
- 如果它不是快捷方式,并且页面处于焦点状态,Chrome 会将事件作为 DOM 输入事件传递到页面中。
- 如果页面中有 jQuery,它会将 DOM 事件转换为它自己的内部事件,匹配侦听器并将内部事件分派给它们。
您的代码仅触发 5 个(内部 jQuery 事件)。
通过directly manipulating DOM events,你可以达到4。
在任何情况下,扩展都不能返回到此堆栈中的 3。
您正在尝试通过代码以迂回方式打开弹出窗口。遗憾的是,这是 simply not possible at all 用于 "ordinary" 扩展 - Chrome 开发团队的一部分有意识的决定。
想想另一种方式来提供 UI,比如 notifications or injecting something in the current page with Content Scripts。
我正在构建一个 Chrome 扩展,并将命令 _execute_browser_action
分配给 Alt+J。我想在 background.js 中模拟这个,它使用
chrome.commands.onCommand.addListener(function(command) { /* ... */ });
我希望通过不同的命令快捷方式调用 _execute_browser_action
,比如 Cmd+Shift+K
在我的 manifest.json 中,我声明了以下内容:
"commands": {
"_execute_browser_action": {
"suggested_key": {
"mac": "Alt+J",
"linux": "Ctrl+Shift+J"
}
},
"asdf" : {
"suggested_key": {
"default": "Ctrl+Shift+K",
"mac": "Command+Shift+K"
},
"description": "asdf"
}
}
这是我的 background.js:
chrome.commands.onCommand.addListener(function(command) {
console.log('onCommand event received for message: ', command);
if (command === "asdf") {
alert("asdf");
var keyPress = jQuery.Event("keypress");
keyPress.altKey = true;
keyPress.ctrlKey = false;
keyPress.which = 74;
//how do I trigger this?
}
});
我想知道如何触发它以便我的 popup.html 打开。
您无法自行触发键盘快捷键。
把它想象成事件的时间轴:
- 一个硬件事件发生,并被OS翻译成输入事件。
- 如果它是 Chrome 注册的全局快捷方式,或者如果 Chrome 获得焦点,则 OS 将事件分派给 Chrome。
- Chrome 检查它是否是已注册的快捷方式。如果是,则触发相应的事件。
- 如果它不是快捷方式,并且页面处于焦点状态,Chrome 会将事件作为 DOM 输入事件传递到页面中。
- 如果页面中有 jQuery,它会将 DOM 事件转换为它自己的内部事件,匹配侦听器并将内部事件分派给它们。
您的代码仅触发 5 个(内部 jQuery 事件)。
通过directly manipulating DOM events,你可以达到4。
在任何情况下,扩展都不能返回到此堆栈中的 3。
您正在尝试通过代码以迂回方式打开弹出窗口。遗憾的是,这是 simply not possible at all 用于 "ordinary" 扩展 - Chrome 开发团队的一部分有意识的决定。
想想另一种方式来提供 UI,比如 notifications or injecting something in the current page with Content Scripts。