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?
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!");
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.