Home > Mobile >  How to capture `Ctrl 1` hotkey on Chrome browser keydown event?
How to capture `Ctrl 1` hotkey on Chrome browser keydown event?

Time:04-03

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()
    }
})

CodePudding user response:

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

CodePudding user response:

This thread seems to have a discussion that might answer your question.

Easiest one to try among the answers there is to use e.preventDefault(); e.stopPropagation(). Hope that thread answers your question.

  • Related