Discussions » Development

Simulate Ctrl+Mouse Click & Keypress Events

§
Posted: 2017-01-31
Edited: 2017-01-31

Simulate Ctrl+Mouse Click & Keypress Events

Below is code that simulate mouse click but without ctrl button. How do I simulate it ctrl+mouse click.

Also I am unable to get keypress to work, if anyone knows how I can get it to work, appreciate it.

var event = new MouseEvent('click', {
                    'view': window,
                    'bubbles': true,
                    'cancelable': true
                });

                link.dispatchEvent(event);

Related pages: https://developer.mozilla.org/en-US/docs/Web/API/Event

§
Posted: 2017-02-02
<h4 href=# id=H style="cursor:pointer">AUTO CLICK</h4>
<script>
function ctrlClick(link){
var event = new MouseEvent('click', {
                    'view': window,
                    'bubbles': true,
                    'cancelable': true,
                    'ctrlKey': true
                });
  return link.dispatchEvent(event);
}   
var link = document.getElementById("H");
link.addEventListener("click",
 function(e){alert('I am clicked with'+(e.ctrlKey?'':'out')+' CTRL')}
);
ctrlClick(link);
</script>

seems working as expected

§
Posted: 2017-02-02
Edited: 2017-02-02

Thank you.

I already tried that on links but I cannot get it to work. Works on buttons but not links. My main goal is to open a tab without focusing on it. FYI: I am using FireFox.

var l = document.createElement("a");
l.href = "http://www.example.com";
document.body.insertBefore(l, document.body.firstElementChild);    
ctrlClick(document.querySelector("a"));
§
Posted: 2017-02-02
Edited: 2017-02-02

Update: It brings up the message but it does not open the link in a new tab. Could be a security feature. I always just tried to see if it opens a tab, never placed a message in there before.

§
Posted: 2017-02-02
It brings up the message but it does not open the link in a new tab.

GM_openInTab

§
Posted: 2017-02-02

Yes, it is a security feature implemented by at least Chrome and Firefox that I know of.

§
Posted: 2017-02-02

That makes sense.

It brings up the message but it does not open the link in a new tab.
GM_openInTab

Thanks, I raised a suggestion for it. It never cross my mind it already exists. :smile:

Post reply

Sign in to post a reply.