Firefox SDK: how “capture” users hotkey in preferences?

点点圈 提交于 2019-12-12 22:15:13

问题


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

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