Assign command keyboard shortcut from popup or options

不羁的心 提交于 2020-06-22 10:56:26

问题


Is it possible with the Chrome API to let users assign a keyboard shortcut from within the extension popup or options page? Without them having to go to extensions page, scroll to the bottom and open keyboard shortcut menu.


回答1:


In Chrome there's no method to assign a shortcut key programmatically, but you can add a button or a link in the extension popup that will open the built-in dialog.

popup.html:

<button id="hotkey">Assign a shortcut key</button>
<script src="popup.js"></script>

popup.js:

document.getElementById('hotkey').onclick = () => chrome.tabs.create({
  url: 'chrome://extensions/configureCommands'
});

Notes:

  • chrome:// URLs can be opened only via chrome/WebExtensions API methods,
    but not via <a href="..."> links directly.

    You can still use a standard <a> link with a click listener shown above; just don't forget to prevent the default click event to avoid an error in the console:

    document.getElementById('hotkey').onclick = event => {
      chrome.tabs.create({url: 'chrome://extensions/configureCommands'});
      event.preventDefault();
    };
    
  • In Opera browser the URL is opera://settings/configureCommands
    You can detect the browser using navigator.userAgent string

  • In Firefox there's currently no way to open this UI programmatically so you'll have to show an instruction to open about:addons page, click the gear icon, then choose "Manage extension shortcuts". However, Firefox allows setting the hotkeys programmatically using browser.commands.update.



来源:https://stackoverflow.com/questions/45347403/assign-command-keyboard-shortcut-from-popup-or-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!