I wonder if there are benign use-cases for simulating mouse clicks using event.initMouseEvent. I found that it is used for creating pop-under ads in the following way:
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
a.dispatchEvent(e);
This code simulates a click on the opening browser window, to force the newly opened window beneath it. Evil.
I’m thinking of simply preventing all simulated clicks in my own browser via a browser extension, but I wonder if I might break useful websites and behavior in the process. Therefore I wonder what situations justify simulating mouse clicks, and if there are big sites that use it in non-evil ways.
3
Let us ignore the fact that the fact a simulated mouse click causes its default action is only in order to maintain backwards compatibility – so the code you mentioned in your example is indeed evil.
There are plenty of legitimate cases where you’d want to simulate mouse events:
- Testing – This is the most important one by far in my opinion. You often want to test that your code reacts correctly. For example, you want to test that when you click a button it becomes inactive (so the user won’t be able to click it again to resubmit an AJAX call for example). Simulating user events is an effective technique to test view logic. Mocking user interaction is overall very useful in testing GUI systems.
- Working with external code – Sometimes you end up working with a plugin or library that has an inconcise API. Sometimes it does not expose the actual functions but does tell you that clicking element X will do Y. The sad truth is that such plugins are more common than we’d like to admit and simulating events is a way to speak to such plugins.
- Scraping – Sometimes you might want to simulate user actions to obtain information for scraping when that information is unavailable otherwise. For example, if you want to extract all the information from a page but that page contains information that requires a click to obtain.
- Automation with Userscripts – Sometimes you end up writing a script that ‘hooks’ on a page and makes working with the page easier for you. In these cases you have no desire to read the actual (often minified and sometimes obfuscated) implementation of the code you’re working against, you just want to simulate a user action.
All these sum up to one thing – working against the user interface and not the backing code. When you want to take a step back and treat the user interface of a page for whatever reason (and these for are by far the most common imo) – simulating a mouse click can be very beneficial.
1
e.initMouseEvent is used by some libraries to simulate click events on mobile phones. This allows code compatiblity between click and touch events.
You can check examples in Ionic or Leaflet