Can Javascript press the Enter key for me?

19,493

Well pressing enter is triggering an event. You would have to figure out which event listener they are listening to. I'll use keyup in the following example:

Assume el is the variable for the element you want enter to be pressed on. I'm not sure how you going to get that element but I'm sure you know.

var evt = new CustomEvent('keyup');
evt.which = 13;
evt.keyCode = 13;
el.dispatchEvent(evt); //This would trigger the event listener.

There's no way to actually simulate a hardware action. It just triggers the event listener.

For example calling el.click() is only calling the callback of the event listener, not actually pressing the key.

So you know how when you add an event listener to an element the first argument is the event object.

el.addEventListener('keyup', function(event) {
   //Do Something
});

Above event is equal to evt when calling dispatchEvent on el

If the programmer used:

el.onkeyup = function(event) {
  //do whatever.
}

It's surprisingly easy.

Just call el.onkeyup(evt);

Because onkeyup is a function.

Why did I use CustomEvent instead of KeyboardEvent because new KeyboardEvent('keyup') return's an object with the properties which and keyCode that can't be rewritten without the use of Object.defineProperty or Object.defineProperties

Share:
19,493

Related videos on Youtube

robberger
Author by

robberger

Current Computer Science student in Minnesota. Looking for an internship for summer 2019.

Updated on September 16, 2022

Comments

  • robberger
    robberger over 1 year

    There's a site that I want to continue to hit enter on while I'm away. Is it possible to do something like

    setInterval(function(){
        //have javascript press the button with a certain id
    },100);
    

    I was thinking of just putting that in the smart search bar so it would run the code.

    • T.J. Crowder
      T.J. Crowder about 9 years
      @Jacques: It's trivial in this case: You just open the web console and type. That code is run in the same environment as the page you're viewing.