Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript enter event doesn't work on google

I'm trying to simulate an 'enter' keypress with javascript for automation.

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-1.10.2.min.js';
script.type = 'text/javascript';
document.body.appendChild(script);
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;

This is the code used to setup the key event (I've tried keydown and keyup as well).

This doesn't seem to work when searching Google. If I type some text and trigger the event on the input field $("[name=q]").trigger(e) nothing happens.

I'm using google to test simulating a "proper" enter event. I hope to use js to automate skype web client.

Does anyone know if it is possible to simulate an actual enter keypress using javascript? I've seen that Selenide's pressEnter() works but it uses webdriver so maybe it's not relevant.

I've also tried native js event triggering

var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
  var e = document.createEvent("KeyboardEvents");
  e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};

dispatchKeyboardEvent($("[name=q]"), 'keypress', true, true, null, 'h', 13, '');

sidenote I am aware that query can be submitted by calling .submit() on the element but that's not what I'm after.

like image 884
Bobbzorzen Avatar asked Jul 20 '15 12:07

Bobbzorzen


2 Answers

As you are referencing document in code, the code should execute when dom is ready.

The event trigger code should execute when the jQuery is loaded, thus write the code in script.onload callback.

As mentioned here, attach the callback before appending the script element to document.body, and also before assigning src to script element.

Working demo : jsFiddle

like image 70
Ashwin Aggarwal Avatar answered Oct 10 '22 05:10

Ashwin Aggarwal


If your code sets the search query string in a single shot, listen for the on change event of the field and call the function.

$("#searchBarId").on("change", function(){
    var e = jQuery.Event("keydown");
    e.which = 13; // # Enter key code value
    $("input").trigger(e)
});

Answer from Definitive way to trigger keypress events with jQuery

Does this solve your issue ?

like image 34
Sarath Chandra Avatar answered Oct 10 '22 05:10

Sarath Chandra