问题
In package.json I have:
"preferences": [{
"name": "hotkeyPopup",
"title": "Hotkey for translating selected text",
"type": "string",
"value": "alt-Y"
}]
And it looks like input type=text. How can I capture user's hotkey combination? This is not cool that user must type by hands words like alt or even worse accel.
Official documentation about hotkeys say nothing about capturing in preferences.
回答1:
In this snippet window can be a content window (tab/iframe/etc) or xul window (nsIDOMWindow)
Very basic very verbose, no tricks. Untested.
function enterHotkeyRecord() {
window.addEventListener('keydown', downed, false);
window.addEventListener('keyup', upped, false);
window.addEventListener('keypress', pressed, false);
}
function exitHotkeyRecord() {
window.removeEventListener('keydown', downed, false);
window.removeEventListener('keyup', upped, false);
window.removeEventListener('keypress', pressed, false);
}
function pressed(e) {
e.preventDefault();
e.stopPropagation();
}
function upped(e) {
e.preventDefault();
e.stopPropagation();
}
function downed(e) {
e.preventDefault();
if (e.repeat) {
// if hold down a key it fires multiple times so ignore it
return;
}
var key = String.fromCharCode(e.code);
var str = [];
if (e.keyCode == 27) {
// user hit escape so lets exit
enterHotkeyRecord();
return;
}
if (e.altKey) {
str.push('Alt');
}
if (e.shiftKey) {
str.push('Shift');
}
if (e.metaKey) {
str.push('Meta');
}
if (e.ctrlKey) {
str.push('Ctrl');
}
str.push(key);
console.log('you pressed:', str.join(' + '));
}
enterHotkeyRecord();
来源:https://stackoverflow.com/questions/32799233/firefox-sdk-how-capture-users-hotkey-in-preferences