【问题标题】:Trigger shortcut in a Chrome extensionChrome 扩展程序中的触发快捷方式
【发布时间】:2016-10-25 21:45:26
【问题描述】:

我正在构建一个 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 打开。

【问题讨论】:

    标签: javascript jquery google-chrome-extension keyboard-shortcuts


    【解决方案1】:

    您无法自行触发键盘快捷键。

    把它想象成事件的时间线:

    1. 发生硬件事件,并由操作系统转换为输入事件。
    2. 如果它是 Chrome 注册的全局快捷方式,或者如果 Chrome 具有焦点,则操作系统会将事件分派给 Chrome。
    3. Chrome 会检查它是否是已注册的快捷方式。如果是,则触发相应的事件。
    4. 如果不是快捷方式,并且页面处于焦点位置,Chrome 会将事件作为 DOM 输入事件传递到页面中。
    5. 如果页面中有 jQuery,它会将该 DOM 事件转换为自己的内部事件,匹配监听器并将内部事件分派给它们。

    您的代码仅触发 5 个(内部 jQuery 事件)。
    通过directly manipulating DOM events,您最多可以达到 4。
    任何情况下扩展都不能在此堆栈中返回 3。

    您正试图从代码中以迂回的方式打开弹出窗口。可悲的是,这是“普通”扩展的 simply not possible at all - Chrome 开发团队的一个有意识的决定。

    考虑另一种提供 UI 的方式,例如 notifications 或使用 Content Scripts 在当前页面中注入一些内容。

    【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    相关资源
    最近更新 更多