Greasy Fork is available in English.

Discussions » Development

Simulate Ctrl+Mouse Click & Keypress Events

§
Posted: 31/01/2017
Edited: 31/01/2017

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: 02/02/2017
<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: 02/02/2017
Edited: 02/02/2017

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: 02/02/2017
Edited: 02/02/2017

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: 02/02/2017
It brings up the message but it does not open the link in a new tab.

GM_openInTab

§
Posted: 02/02/2017

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

§
Posted: 02/02/2017

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.