Javascript enter event not working in google

I am trying to simulate pressing 'enter' 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 configure the key event (I also tried keydown and keyup).

This does not work when searching on Google. If I type text and fire an event in the input field $("[name=q]").trigger(e) , nothing happens.

I use google to test the simulation of the "correct" event input. I hope to use js to automate the skype web client.

Does anyone know if it is possible to simulate an actual input key press using javascript? I saw that Selenide pressEnter() works, but it uses webdriver, so maybe this is not relevant.

I also tried running js event jQuery

 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 know that a request can be sent by calling .submit () for an element, but this is not what I am after.

+7
javascript jquery events
source share
3 answers

As you refer to document in code, the code should execute when dom is ready.

Event triggering code should be executed when jQuery loads, thus writing code in the script.onload .

As mentioned here , add a callback before adding the script element to document.body , as well as before assigning the src script element.

Working demo : jsFiddle

+1
source share

If your code sets the search query string in one shot, listen for the change event in 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 Determining how to trigger keypress events using jQuery

Does this solve your problem?

+1
source share
 <select id="ss"> <option value="1">1</option> <option value="2">2</option> </select> $('#ss').keypress(function(e){ var p = e.keyCode; alert(p); if(p==13){ alert('enter was pressed'); } }); 
0
source share

All Articles