-2

How does a website recognize keystrokes, mouse movement? Is there a way to send a command ("like pressing down your left mouse button) via JavaScript, without actually pressing down your mouse button?

If my question is too unclear, I'm very happy to explain further. I'm new and just trying to start somewhere but am lost.

Can you recommend me some good learning material, so I can read into it, thank you very much.

moeux
  • 191
  • 15
  • The site has event listeners attached to elements. You can dispatch your own events programatically, or trigger the site's listeners programatically – CertainPerformance May 17 '20 at 20:07
  • 1
    Does this answer your question? [Is it possible to simulate key press events programmatically?](https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically) – pacukluka May 17 '20 at 20:10
  • @CertainPerformance I'm not really educated in server to client communication, so the website has event listeners attached to elements which are triggered by the client, let's say via a mouse click on the "Search" button on Google? Would the website even accept foreign events? How would those be sent to the server? – moeux May 17 '20 at 20:44
  • @LukaKostic it tells me how the syntax etc. looks. Firstly thanks for that! How would those scripts be executed and actually used on a website? – moeux May 17 '20 at 20:45
  • Nothing in that is server-client communication - it's all on the client-side – CertainPerformance May 17 '20 at 20:57
  • Well i wrote you a lengthy answer on how they are used on a website and how to simulate them. You could have found all of this by just searching, you know. @M0e – pacukluka May 17 '20 at 21:30
  • @LukaKostic Your answer wasn't loaded in yet on my end. Thank you very very much. I appreciate it! – moeux May 17 '20 at 23:24

1 Answers1

1

Mouse, Keyboard, and other Events

Sites recognize keyboard and mouse 'events' by subscribing a function to them.

You can do that thru html like so: onkeypress="keypressFunction()", onmousemove="mousemoveFunction()", onclick="clickFunction()"... and other events

<div onclick="clickFunction()">Clickable</div>

Of course these functions keypressFunction(), mousemoveFunction(), clickFunction() need to exist somewhere in your site, whether inside

<script>
function clickFunction(){ alert('clicked!') }
</script>

or included from file: <script src="myscripts.js"></script> .

You can also subscribe to events using just javascript:

//Write `document` instead of `element` to apply to whole document
//Or you can find element by id like document.getElementById('id')
//You can of course use any other method of finding elements such
// as querySelector or use variables you already made before
element.onkeypress = function(eventArgs){
    eventArgs = eventArgs || window.event;
    // use eventArgs.keyCode to get which key
};

Or, more common and safe, subscribe with addEventListener:

element.addEventListener('keypress', function(eventArgs){
    eventArgs = eventArgs || window.event;
    // use eventArgs.keyCode to get which key
});

Note you dont have to write the prefix on in the event names (eg onkeypress) if using addEventListener.

You can of course also use already made functions:

element.onkeypress = myFunction;

and

element.addEventListener('keypress', myFunction);

All of these events usually pass an event-specific parameter to give more data about what exactly happened in the event.

For example, onclick passes MouseEvent args, so you can know where the mouse was (X and Y coords on screen) when the thing was clicked, were the alt/shift/ctrl keys held, and which mouse button was clicked (left, right, middle).

Keyboard events have their own event args with info on which keyboard key was pressed, if its being held, and so on. You can find all event arguments here.

Simulating events

Some basic events, such as a mouse click on an element, can be simulated with just element.click();, but that doesnt give you much control over the event args that are getting passed.

To properly send an event, you need to create a browser event object, and dispatch it on an element:

//Call oncontextmenu (right mouse click) on an element:
var element = document.getElementById('Id_here');
if (window.CustomEvent) {
    element.dispatchEvent(new CustomEvent('contextmenu'));
} else if (document.createEvent) {
    var ev = document.createEvent('HTMLEvents');
    ev.initEvent('contextmenu', true, false);
    element.dispatchEvent(ev);
} else { // Internet Explorer
    element.fireEvent('oncontextmenu');
}

With that event object you can pass some data, here is simulating a keypress:

var element = document.getElementById('Id_here');
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";

keyboardEvent[initMethod](
  "keydown", // event type: keydown, keyup, keypress
  true,      // bubbles
  true,      // cancelable
  window,    // view: should be window
  false,     // ctrlKey
  false,     // altKey
  false,     // shiftKey
  false,     // metaKey
  65,        // keyCode: unsigned long - the virtual key code, else 0. 65 - 'a'
  0          // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
);
element.dispatchEvent(keyboardEvent);

Jquery gives some nice functions to make simulating events easier, but you can find those all over stack overflow, not even to mention google. Just search js simulating keypress/mouse, js subsribe to key/mouse event, and all the other things you can imagine.

pacukluka
  • 728
  • 4
  • 18