Search code examples
javascripthtmlui-automationnightmare

Function that automatically press's a key Javascript


How would I best go about writing a function that press's a key?
(I want it to press Tab in particular)


Solution

  • The key is called CHARACTER TABULATION key, the unicode for that is \u0009.

    I'll be using a sample keyboard test page and a very simple script as example. We can use the function .type() to send \u0009 on the page. You can send any character as keyboard input and it should be working perfectly fine.

    const Nightmare = require('nightmare');
    const nightmare = new Nightmare({ show: true });
    (async function() {
      await nightmare
        .goto('http://en.key-test.ru/')
        .wait(500)
        .type('body', '\u000d') // press Enter
        .type('body', '\u0009') // press Tab
        .wait(500)
        .screenshot('example.png')
        .end()
        .then(()=>{console.log('done pressing keys')})
    })();
    

    The result is as below. Which presses Enter and then Tab key. enter image description here

    Surely you won't need a function for that, right? after all you can use

    nightmare.type('body', '\u0009')
    

    anywhere and it should be what you need.