How do I simulate mouse events in the browser chrome?

So I wanted to write some unit tests that would use simulated mouse events.
But I can’t seem to trigger anything when targeting the browser chrome.
I did this simple test to see if I could trigger a tab activation, but nothing happens.

gBrowser.tabs[2].dispatchEvent( new MouseEvent("click") );

Not even a console message…

Anybody know what’s going on?

1 Like

You can use this: https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent

If you want to simulate drags and other complex stuff you will have to use ChromeUtils and EventUtils however these are meant for testing so they haven’t been made compatible for addon/jsm sandbox scope.

https://dxr.mozilla.org/mozilla-central/source/testing/mochitest/tests/SimpleTest/EventUtils.js

https://dxr.mozilla.org/mozilla-central/source/testing/mochitest/tests/SimpleTest/ChromeUtils.js

So I started working on ChromeUtils and got things i needed to work, to work:

For ChromeUtils, the element needs to be physically visible on the users monitor. The tab has to be focused, im not sure but the browser window of that tab may also need focus. The element must be visible in the scroll viewport.

Thanks,

I did some additional messing around, didn’t try your ChromeUtils.
But I got some spiffy behavior from trying to mimic drag and drop.
So I decided that mocking the dataTransfer object would be good enough for my tests.

let dropEvent = new window.MouseEvent("drop");
dropEvent.dataTransfer = {
    types: ["application/x-moz-tabbrowser-tab"],
    mozSourceNode: viewFor( tab )
};
target.dispatchEvent( dropEvent );

And much simpler.

1 Like

Wow that’s really cool! I’ll have to try that! I only went to ChromeUtils because i couldn’t get this to work. Will try and let you know how it works out when i do :slight_smile:

Hi, is there something similar for webextensions?

For sure there is not such a thing for webexts.