问题
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