Search code examples
htmlgoogle-chromedom-eventskeydownhotkeys

How to capture `Ctrl+1` hotkey on Chrome browser keydown event?


I'm now developing a website for mindmap manipulation, and now want to make some hotkeys to make operations better.

In XMind, Ctrl+1 stands for adding a label with number 1, but I found the keydown event cannot capture the event. Instead, Ctrl+1 leads to activating the first Chrome tab, even though I call the e.preventDefault().

So the priority of the chrome browser is the most significant so cannot be intercepted. If I want to make the Ctrl+1 hotkey act as expect, is there any solution?

document.addEventListener('keydown', function(e) {
    if (e.ctrlKey && e.code === 'Digit1') {
        // ...
        e.preventDefault()
    }
})

Solution

  • document.addEventListener('keydown', function (e) {
        console.log(e.keyCode)
        if (e.ctrlKey && [49, 50, 51].includes(e.keyCode)) {
            e.preventDefault()
            console.log('hahahah')
        }
    })