MagTun
MagTun

Reputation: 6185

Chrome extension: adding a keyboard shortcut with Alt with addEventListener('keypress')

I am doing this open source chrome extension and I would like to add a shortcut so that when the extension is open and I press Alt+C, then the content of a div is copied to my clipboard.

I am able to add shortcuts with a simple addEventListener:

var inputText = document.getElementById('textareaSource');
    inputText.addEventListener('keypress', function (e) {
        if (e.keyCode == 99) {        
            // alert("You pressed C!");
        }
});

But apparently this way of adding shortcut doesn't allow shortcuts containing Alt. I tried this but I didn't get any alert:

if (e.altKey || e.ctrlKey || e.shiftKey)
    alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}

I am also able to add shortcuts via manifest/background.js (following this and this). This time, the Alt+C works but it can be triggered everywhere on Chrome and not only when my extension is opened.

Is there a way to get a middle ground: adding a shortcut containing Alt that is only triggered when my extension is opened?

Upvotes: 1

Views: 741

Answers (1)

FZs
FZs

Reputation: 18619

The keypress event won't fire when a modifier key has been pressed, additionally, now it is deprecated.

As it say on the MDN, you should consider using keydown event instead, which supports the way you've tried.

event.keyCode is also deprecated, and event.key should be used instead.

So this code should work:

var inputText = document.getElementById('textareaSource');
    inputText.addEventListener('keydown', function (e) {
        if (e.key == "c" && e.altKey) {        
            // alert("You pressed Alt + C!");
        }
});

Upvotes: 1

Related Questions