The Problem
For site testing, I am attempting to emulate a middle click (or scroll wheel click) on an element like the one below, using JS that is based on some other answers on here.
HTML:
<a
id="example-link" href="https://www.google.com/"
target="_blank"
onclick="window.open('https://www.google.com/', '',
'width=500, height=500, resizable=1, scrollbars=1');
return false;">
<span>Middle Click Me</span>
</a>
JS (looking to change something here):
var middleClick = new MouseEvent( "click", { "button": 1, "which": 2 });
jQuery("#example-link")[0].dispatchEvent( middleClick );
The issue is shown in this jsfiddle.
- Note that a regular click should normally dispatch a popup. jsfiddle is catching the popup and opening it in a new tab.
- jsFiddle is used instead of a stackoverflow fiddle to avoid confusion, as the stack overflow fiddle doesn't properly handle window.open().
Compare 1) middle-clicking manually to 2) running the code to emulate a click.
The problem is, when I trigger the middle click programmatically, it triggers both the onclick method of opening a new window, as well as opening the link in a new tab (creating both a popup and a tab instead of just a tab). If this link is middle clicked manually, the popup will not trigger.
The Question
Is there a better way of emulating middle clicks (preferably cross-browser compatible)? The way it is written, I can't really get the MouseEvent script to accurately emulate manual middle clicks.
Edit: unfortunately, I can't change the HTML object or modify the DOM for the purpose of testing integrity, so I would prefer that the onclick tag stays on the element.