4

There are some web,I type the code below not working.For example,I type the code in console at Bing(a search engine)

var event;
event = document.createEvent('Event');
event.initEvent("keypress", true, true);
event.view = window;
event.keyCode = 13;
event.which = 13;
event.charCode = 13;
event.code = "Enter";
event.key = "Enter";
event.bubbles = true;

and i have already type some text in the search bar, the element's id is "sb_form_q",so

var element = document.getElementById("sb_form_q");
element.dispatchEvent(event);

it will return true, but actually nothing happen. I have tried many webs, some working, some not working, and i don't know why.

2018/8/3 update:

I know why some web page dispatch "Enter" event don't work,cause the input is not submit by "Enter" key, but by submit or onsubmit event.

Ivan Wu
  • 191
  • 1
  • 10
  • I am writing a google extension, and i want to auto type the text and submit it, now i can successfully auto type the text, but can't dispatch "enter" – Ivan Wu Jul 30 '18 at 09:14
  • Use JavaScript to simulate press "Enter" key is important for me – Ivan Wu Jul 30 '18 at 10:04

2 Answers2

1

Please find below example as well for Enter keyword.

window.onload = function(){
    var ev = document.createEvent('Events');
    ev.initEvent('keypress', true, true);
    ev.keyCode = 13;
    ev.which = 13;
    ev.charCode = 13;
    ev.key = 'Enter';
    ev.code = 'Enter';
    var eventReturns = document.querySelector('#input-event').dispatchEvent(ev);    
    var Inputvalue = document.getElementById('input-event').value;
    console.log({isdispatch: eventReturns, value: Inputvalue}); 
}
<input type="text" id="input-event" value="Hello World" />
Mayur Shedage
  • 1,027
  • 2
  • 11
  • 19
  • keypress event with key **`Enter`** – Mayur Shedage Jul 30 '18 at 10:48
  • yeah, it can work like my code, but in search engine "Bing" or some webs, still not working.My purpose is that i can use the code in every web. – Ivan Wu Jul 31 '18 at 01:59
  • I have tested with below Chrome, Firefox, Opera and Edge etc. – Mayur Shedage Jul 31 '18 at 05:50
  • [Inline Link](cl.ly/0G1D2j0y0N1k) (cl.ly/3S1f3G2x0y1P)(cl.ly/442V0f2n1C2I)(cl.ly/3S3T0a0r2j1L) – Mayur Shedage Jul 31 '18 at 05:57
  • Sorry for my poor english,the thing i think is i want to execute in webs(such as Ask.com,and Bing.com,etc) in the search box, not web browsers. i find it is difficult to test in console in web, because i write it in my plugin . However,thanks a lot. – Ivan Wu Jul 31 '18 at 07:28
0

Please check the below code it's working.

function MouseEvent(event) {
 var x = document.createEvent("MouseEvent");
 x.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

 document.getElementById("myDiv").dispatchEvent(x);
 console.log(document.getElementById("myDiv").dispatchEvent(x));
}
<div id="myDiv"></div>
<button onclick="MouseEvent(event)">Simulate click</button>
Mayur Shedage
  • 1,027
  • 2
  • 11
  • 19