-1

I am trying to write a script that triggers, on page load, an even that presses and holds down the Space key for 5 seconds straight. After those 5 seconds the key goes up. Is this possible?

Please note that everything must happen without any user interaction.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • But what is this space down supposed to do? Maybe instead if triggering a key down in order to trigger a function or a behaviour, you can directly trigger that function or behaviour (XY problem) – Jeremy Thille Jan 14 '20 at 15:40
  • Hi Jeremy, the "space" keyboard key just need to be auto pressed and be held down for 5 seconds. (I have my use for it), thanks – MiniMax Jan 14 '20 at 15:42
  • Well, you are just repeating your question without answering mine – Jeremy Thille Jan 14 '20 at 15:45

1 Answers1

0

You can simulate a fake user input by calling the dispatchEvent function (see also this StackOverflow thread). However, faking the holding down a key for five seconds could be problematic. Of course, you could use a setInterval function to re-dispatch the keyboard event every x milliseconds:

setInterval(() => {
  document.dispatchEvent(keyboardEvent);
}, 100);

But instead you should consider thinking about a different solution without simulating the Space down event at all. Which part of your code would be affected if the Space key is pressed? Just rewrite that piece of code so that it performs a special action when the page is loaded.

It could also be helpful to see some of your script code.

SparkFountain
  • 2,110
  • 15
  • 35