Poll to check if modifier key is down

Is there any recommended way to poll to see if the modifier key is down?

I’d like to be able to check if the shift key is down and indicate that in my plugin.

1 Like

Just to clarify: Are you asking about a way to check this “globally” or within the plugin UI?

Keyboard events are supported, including CTRL and SHIFT:
https://www.adobe.io/xd/uxp/uxp/reference-js/Global%20Members/HTML%20Events/KeyboardEvent/

Is it possible to get if only shift key is down? Here’s what I’m using:

window.addEventListener("keydown", function(event) {
    log("key shift event", event.shiftKey)
})

This event is dispatched when pressing keys that are not modifier keys.

If I press shift, alt, control or command I don’t receive an event.

Here’s a second attempt using async to poll for changes:


var checkForShiftKey = false;

/** Open dialog */
async function openDialog(selection, documentRoot) {
    pollForShift(); // leave off the await here
    var dialog = await model.dialog.showModal();
}

// check if shift key is down
async function pollForShift() {
   checkForShiftKey = true;
   
   for (var i=0; model.checkForShiftKey; i++) {
        await sleep(500);

        var keyboardEvent = new KeyboardEvent("keydown");
        console.log("keyboardEvent.shiftKey" + keyboardEvent.shiftKey); // undefined

        var modifierState = keyboardEvent.getModifierState();
       console. log("modifierState", modifierState); // false
    }
}

/**
 * Milliseconds to wait. Put this in an async function and call await sleep(duration)
 * @param {Number} ms 
 **/
 function sleep(ms) {
	return new Promise(resolve => setTimeout(resolve, ms))
}

In the plugin environment. My plugin has a lot of buttons and if you press Shift you get an alternate set of behaviors. I’d like to show alternate information and help when the user presses the shift key.

I do not think it is possible to have an event in response to only the shift key being pressed. Keyboard events happen when characters are typed, and shift is not a character, but a modifier to a character. Your code is correct to detect if the shift key was pressed along with another key.

If the goal is to change the plugin’s panel to show different controls, then my suggestion is to instead provide a checkbox to change state.