Search code examples
javascripthtmleventsgreasemonkeykeypress

Simulate an enter key press in Javascript with GreaseMonkey


What I want to do is fill up an input field, focus on it and press Enter to submit it. All of this automatically with GreaseMonkey on a specific page.

Here is what I have so far, the field is filled up, but I can't get the keypress to work.

var my_email = "[email protected]";

var field = document.getElementById('email');

var key_to_press = new Array;
key_to_press["key"] = "Enter";
key_to_press["keyCode"] = "13";
var ev = new KeyboardEvent("pressEnter", key_to_press);

field.value = my_email;

setTimeout(function() {
  field.focus();
}, 2000);

setTimeout(function() {
  field.dispatchEvent(ev);
}, 2000);

Here is some of the HTML from the page:

<div class="form-group no-label required">    
    <label class="control-label" for="invite-email"></label>
    <div class="input-group">
        <input id="hiddenKid" type="hidden" value="BUXB4U"></input>
        <input id="email" class="form-control" type="email" placeholder="E-mail Address" data-type="email" name="invite-email"></input>    
    </div>    
</div>
<div id="submit_email" class="btn btn-submit-invite"></div>

Notice that there is also a button to submit the email, I could use it but I really don't know how to, since it is just a div probably handled by some other JS from the website...

So does anyone know how can I make the enter keypress happen, or maybe click the button?


Solution

  • Finally I managed to click the button. .click() wasn't working because the event use .tap() so here is what I just did:

    $('#submit_email').tap();