问题
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 usingnavigator.userAgent
stringIn 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