Can Javascript press the Enter key for me?

痞子三分冷 提交于 2020-01-02 04:04:42

问题


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.


回答1:


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




回答2:


You can try this:

setInterval(function(){
    $('#some_id').click();
},100);

it will execute click event for the button with id some_id.




回答3:


Clicking a button with Javascript is easy. First find the element using document.querySelector or document.getElementById:

document.querySelector("#myButton");

Every HTML element then got a function called click:

document.querySelector("#myButton").click();


来源:https://stackoverflow.com/questions/29719419/can-javascript-press-the-enter-key-for-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!