简体   繁体   English

以编程方式触发键盘快捷键,例如在 Gmail 中

[英]Programmatically trigger keyboard shortcuts, e.g. in Gmail

Is there any way to programmatically trigger keyboard shortcuts from Javascript?有没有办法以编程方式从 Javascript 触发键盘快捷键? For example, take gmail.com, where pressing 'e' will archive the selected email.例如,以 gmail.com 为例,其中按“e”将归档选定的 email。

Could I write any type of code (say in a Chrome Extension) that can simulate the user pressing 'e' on the keyboard?我可以编写任何类型的代码(比如在 Chrome 扩展程序中)来模拟用户在键盘上按“e”吗?

Eg I tried copy-pasting something like this in the Chrome console:例如,我尝试在 Chrome 控制台中复制粘贴类似这样的内容:

document.body.addEventListener('keydown', function(event) {
  console.log('key detected: ', event);
});

document.body.addEventListener('click', () => {
  console.log('click...');
    document.body.dispatchEvent(new KeyboardEvent('keydown', {
    'key': 'e',
    'keyCode': 69,
    'which': 69,
    'code': 'KeyE',
    'isTrusted': true,  // this has no effect
    'bubbles': true,
    'cancelable': true,
    'view': window,
    'charCode': 0,
  }));
});

So any click on the page will print the key, which looks the same as pressing 'e' on the keyboard.因此,在页面上的任何点击都会打印出该键,这看起来与在键盘上按“e”相同。 But the click event keypress does not trigger the 'archive' feature in Gmail.但是点击事件按键不会触发 Gmail 中的“存档”功能。

Is it that the event is not trusted, and it's not possible to do what I had intended?是不是事件不被信任,无法按照我的意愿去做?

I found a working solution that does what I need.我找到了一个可以满足我需要的有效解决方案。 It works only in a Chrome Extension (there could be similar methods for Firefox Extensions and other browsers).它仅适用于 Chrome 扩展程序(Firefox 扩展程序和其他浏览器可能有类似的方法)。 I could not find any native JavaScript only solution (I believe it's not possible by design due to untrusted events).我找不到任何本机 JavaScript 唯一解决方案(我相信由于不受信任的事件,这在设计上是不可能的)。

In any case, the Chrome Extension solution works as follows:无论如何,Chrome 扩展解决方案的工作原理如下:

// Attach debugger to the active tab (it's the only way to send
// trusted events.
chrome.debugger.attach({tabId: tab.id}, '1.2', () => {
  // Create shortcut args and send to the tab.
  const eventArgs = {
    'modifiers': 0,
    'text': 'e',
    'unmodifiedText': 'e',
    'key': 'e',
    'code': 'KeyE',
    'windowsVirtualKeyCode': 69,
    'type': 'keyDown'
  };
  chrome.debugger.sendCommand(
    {tabId: tab.id}, 'Input.dispatchKeyEvent', eventArgs,
      (result) => {
        if (chrome.runtime.lastError) {
          console.warn('Error sending the shortcut to active tab:',
              chrome.runtime.lastError);
        }
        chrome.debugger.detach({tabId: tab.id});
      });
    });
  });

Note that the debugger can't attach on some very specific websites like gmail.com or drive.google.com when users have a Chrome App installed for these sites.请注意,当用户为这些网站安装了 Chrome 应用程序时,调试器无法附加到某些非常特定的网站,例如 gmail.com 或 drive.google.com。 You may see an error like:您可能会看到如下错误:

Cannot attach to this target.

See https://bugs.chromium.org/p/chromium/issues/detail?id=885025 for details.有关详细信息,请参阅https://bugs.chromium.org/p/chromium/issues/detail?id=885025 The only workaround is to uninstall the Chrome Apps for the target sites.唯一的解决方法是卸载目标站点的 Chrome 应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 JavaScript 以编程方式调度键盘(例如按键)事件 - Programmatically dispatch keyboard (e.g. keypress) events using JavaScript 通过 Dropzone 以编程方式上传/添加文件,例如 Selenium - Programmatically upload / add file via Dropzone e.g. by Selenium 删除 JQuery/Javascript 键盘挂钩(例如 Portfolio Slide Gallery) - Removing JQuery/Javascript keyboard hooks (e.g. Portfolio Slide Gallery) 如何防止屏幕阅读器焦点(不是指键盘焦点)离开预定义区域(例如,模态) - How to prevent screen reader focus (not referring to keyboard focus) from leaving predefined area (e.g., modal) Firefox:添加自定义键盘快捷方式,例如使用“显示密码”打开“保存的登录名” - Firefox: Add custom keyboard shorcut e.g. to open 'Saved Logins' with 'Show Passwords' 我如何以编程方式查看网站发出的请求(例如 API 或资源请求) - How can I programmatically see what requests (e.g. API or resource requests) are being made by a website AngularJs facebook喜欢提及:如何在没有触发字符的情况下开始提及建议,例如“ @” - AngularJs facebook like mention: how to start mention suggestions without the trigger character e.g. '@' 如何从非角度上下文(例如D3事件)触发角度变化? - How to trigger an angular change from a non-angular context e.g. from a D3 event? 当处理程序访问 originalEvent 时触发事件(例如通过 jQuery) - Trigger event (e.g. via jQuery) when handler accesses originalEvent 如何在select2单选中触发标签创建(例如,当按下相邻按钮时)? - How to trigger tag creation in select2 single select (e.g. when adjacent button is pressed)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM