I'm trying to simulate a mouse click event in IE/FireFox browsers when ctrlKey tag is true. I've googled it a lot, but I cannot find why my code isn't working. What supposed to happen: - triggerClick should click the link (that is fine in both IE & FF) - triggerClickCtrl should open the link in a new tab (in IE - it does the same as the buttom triggerClick, and in FF it does nothing). - triggerClickShift should open the link in a new window (in IE - it does the same as the buttom triggerClick, and in FF it does nothing). Note: this code works in chrome, but it doesn't work in IE11 and FireFox.

any suggestions? Thanks.

<!DOCTYPE html>
<html>

<p><a id = 'bingLink' href = "http://www.bing.com">Bing</a></p>

<button onclick=triggerClick()>triggerClick</button>
<button onclick=triggerClickCtrl()>triggerClickCtrl</button>
<button onclick=triggerClickShift()>triggerClickShift</button>

<script>
    function triggerClick()
    {
        simulateClick(false, false, false);
    }
    function triggerClickCtrl()
    {
        simulateClick(true, false, false);
    }
    function triggerClickShift()
    {
        simulateClick(false, true, false);
    }

    var simulateClick = function (ctrl, shift, isMiddle) {
        var evt = document.createEvent('MouseEvents');
        evt.initMouseEvent('click', true, true, window, 0, 0, 0, 10, 10, ctrl, false, shift, false, isMiddle ? 1 : 0, null );
        document.getElementById('bingLink').dispatchEvent(evt);
    }

</script>

</body>

</html>

Dani AI

Generated

Short answer: you cannot fake a Ctrl+click well enough to make IE11 or Firefox open a new tab/window. The modifier flags you set on a synthetic MouseEvent are visible to your JS listeners, but the browser does not treat that as a real user gesture. In modern browsers, actions like opening new tabs/windows are gated behind “user activation,” which requires an isTrusted event generated by an actual user input. Events you create and dispatch from script are untrusted, so the browser ignores those tab/window side-effects. See MDN’s notes on deprecated initMouseEvent, user activation, and window.open’s requirement for a real user interaction. MouseEvent.initMouseEvent() is deprecated. Features gated by user activation. Window.open requires transient activation.

What to do instead (and this aligns with what was circling around): handle a real click from the user, check modifiers, and decide yourself how to open. This keeps you inside the user-gesture call stack, so popup blockers will allow it.

const link = document.getElementById('bingLink');

link.addEventListener('click', function (e) {
  // Cmd on macOS behaves like Ctrl on Windows/Linux
  const ctrlCmd = e.ctrlKey || e.metaKey;

  if (ctrlCmd) {
    window.open(this.href, '_blank', 'noopener'); // open new tab
    e.preventDefault();
  } else if (e.shiftKey) {
    window.open(this.href, '_blank', 'popup,width=900,height=700'); // request a new window
    e.preventDefault();
  }
  // else: let normal navigation proceed
});

Notes:

  • Browser settings can still choose whether “new” means tab or window, so you cannot guarantee the container. Window.open.
  • IE11 predates the modern event constructors; even there, synthetic events are not trusted, so they will not grant you the Ctrl/Shift tab-opening behavior. Rely on an actual click, not a dispatched one. Event.isTrusted (overview on MDN Event page).

Recommended Answers

All 11 Replies

I see this question kicking around since about 2011 but no clear answer.

However as I read https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode I don't see an event for the keycode you are sending.

If you wanted to learn what Mozilla is listening for you might have to get into the source but the big clue here why it didn't respond is in the keycode article.

How to fix? May had to similate the control key down, then your mouse click down, up then a control key up.

Thanks for you answer.
I didn't send keyboard event for ctrlKey, but sent it inside the mouseEvent.

event.initMouseEvent(type, canBubble, cancelable, view,
                     detail, screenX, screenY, clientX, clientY,
                     ctrlKey, altKey, shiftKey, metaKey,
                     button, relatedTarget);

The function 'triggerClickCtrl' send initMouseEvent with ctrlKey=true. But, as mentioned before, it doesn't seem to work.
I can write mechanism which send keyPress event, but I rather understand why this one isn't working.

"understand why this one isn't working."

Remember that this has been kicked around in prior discussions so I went looking for what keycodes Mozilla and IE respond to. The keycode you tried didn't look to be in the article I linked to. Maybe there's another for mouse? Look for a document on that area.

I've tried to use MouseEvent() as describe in Mozilla site.

    var simulateClick = function (ctrl, shift, isMiddle) {
        var element = document.getElementById('bingLink');
        var evt = new MouseEvent("click", {
            view: window,
            bubbles: true,
            cancelable: true,
            clientX: 10,
            clientY: 10,
            ctrlKey: true
        });
        element.dispatchEvent(evt);
}

This is the new simulateClick function. But I still get the same result. It doesn't perform the ctrlKey press during click.

Even dispatch keyboard (ctrlKey) and mouse (click) wasn't worked.
Any other suggestions?

At this point, now that you are squarely into the non-deprecated API, I have to wonder if Adsense's "Automated clicking tools," code is blocking you. Your code noted a Bing link which is not something one should normally automate. There's a lot out there about Adsense building in defenses from what you are doing. Test your clicker on non-ad links and buttons.
More at http://adsense.blogspot.com/2008/08/defining-invalid-clicks-and-click-fraud.html

Have a specific one in mind? I dont realy care which link. Just wanted to cause the browser simulate open new tab while clicking a link with ctrl..

Hmm, who said the control+click opens a new tab? That result is not assured as I can change that in the browser settings.

As to a specific one, why not this page (Daniweb.com) Try it on the <DANIWEB> link. And remember that browser settings can thwart this action. I can disable, cause it to open tab or window.

That said, why does this need to work in all browsers? Tell some story.

I don't really care what will happen when clicking mouse+ctrl. I just want to achieve the same result as manual clicking.
It also doesn't work with this site :\

It looks good except in the areas of where anti-robot-clicking is imposed. There's been a lot of work to stop automated clickers since those are not worthy clicks. I was incorrect to tell you to try it here since well, you know why.

You may have to test this on your own local web site that is clean and not going to block fake or automated clicks.

-> Did you try this with AutoIT?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.