EventUtils documentation
EventUtils
’ methods are available in all browser mochitests on the EventUtils
object.
In mochitest-plain and mochitest-chrome, you can load
"chrome://mochikit/content/tests/SimpleTest/EventUtils.js"
using a regular
HTML script tag to gain access to this set of utilities. In this case, all the
documented methods here are not on a separate object, but available as global
functions.
Mouse input
- sendMouseEvent(aEvent, aTarget, aWindow)
Send a mouse event to the node aTarget (aTarget can be an id, or an actual node) . The “event” passed in to aEvent is just a JavaScript object with the properties set that the real mouse event object should have. This includes the type of the mouse event. Pretty much all those properties are optional. E.g. to send an click event to the node with id ‘node’ you might do this:
sendMouseEvent({type:'click'}, 'node');
- EventUtils.synthesizeMouse(aTarget, aOffsetX, aOffsetY, aEvent, aWindow)
Synthesize a mouse event on a target. The actual client point is determined by taking the aTarget’s client box and offseting it by aOffsetX and aOffsetY. This allows mouse clicks to be simulated by calling this method.
- aEvent is an object which may contain the properties:
shiftKey, ctrlKey, altKey, metaKey, accessKey, clickCount, button, type. For valid type`s see nsIDOMWindowUtils’ `sendMouseEvent.
If the type is specified, an mouse event of that type is fired. Otherwise, a mousedown followed by a mouseup is performed.
aWindow is optional, and defaults to the current window object.
Returns whether the event had preventDefault() called on it.
- static synthesizeMouseAtCenter()
- Version of synthesizeMouse that uses the center of the target as the mouse
location. Arguments and the return value are the same.
- synthesizeNativeMouseEvent(aParams)
There are 3 mutually exclusive ways of indicating the location of the mouse event: set
atCenter
, or passoffsetX
andoffsetY
, or passscreenX
andscreenY
. Do not attempt to mix these.- Arguments:
aParams (object)
aParams.type (string) – “click”, “mousedown”, “mouseup” or “mousemove”
aParams.target (Element) – Origin of offsetX and offsetY, must be an element
aParams.atCenter (Boolean) – Instead of offsetX/Y, synthesize the event at center of target.
aParams.offsetX (Number) – X offset in target (in CSS pixels if scale is “screenPixelsPerCSSPixel”)
aParams.offsetY (Number) – Y offset in target (in CSS pixels if scale is “screenPixelsPerCSSPixel”)
aParams.screenX (Number) – X offset in screen (in CSS pixels if scale is “screenPixelsPerCSSPixel”), Neither offsetX/Y nor atCenter must be set if this is set.
aParams.screenY (Number) – Y offset in screen (in CSS pixels if scale is “screenPixelsPerCSSPixel”), Neither offsetX/Y nor atCenter must be set if this is set.
aParams.scale (String) – If scale is “screenPixelsPerCSSPixel”, devicePixelRatio will be used. If scale is “inScreenPixels”, clientX/Y nor scaleX/Y are not adjusted with screenPixelsPerCSSPixel.
aParams.button (Number) – Defaults to 0, if “click”, “mousedown”, “mouseup”, set same value as DOM MouseEvent.button
aParams.modifiers (Object) – Active modifiers, see _parseNativeModifiers
aParams.win (Window) – The window to use its utils. Defaults to the window in which EventUtils.js is running.
aParams.elementOnWidget (Element) – Defaults to target. If element under the point is in another widget from target’s widget, e.g., when it’s in a XUL <panel>, specify this.
- synthesizeMouseExpectEvent(aTarget, aOffsetX, aOffsetY, aEvent, aExpectedTarget, aExpectedEvent, aTestName, aWindow)
Similar to synthesizeMouse except that a test is performed to see if an event is fired at the right target as a result.
aExpectedTarget - the expected originalTarget of the event. aExpectedEvent - the expected type of the event, such as ‘select’. aTestName - the test name when outputing results
To test that an event is not fired, use an expected type preceded by an exclamation mark, such as ‘!select’. This might be used to test that a click on a disabled element doesn’t fire certain events for instance.
aWindow is optional, and defaults to the current window object.
- synthesizeWheel(aTarget, aOffsetX, aOffsetY, aEvent, aWindow)
Synthesize a wheel event on a target. The actual client point is determined by taking the aTarget’s client box and offseting it by aOffsetX and aOffsetY.
- aEvent is an object which may contain the properties:
shiftKey, ctrlKey, altKey, metaKey, accessKey, deltaX, deltaY, deltaZ, deltaMode, lineOrPageDeltaX, lineOrPageDeltaY, isMomentum, isNoLineOrPageDelta, isCustomizedByPrefs, expectedOverflowDeltaX, expectedOverflowDeltaY
deltaMode must be defined, others are ok even if undefined.
expectedOverflowDeltaX and expectedOverflowDeltaY take integer value. The value is just checked as 0 or positive or negative.
aWindow is optional, and defaults to the current window object.
- EventUtils.synthesizeWheelAtPoint(aLeft, aTop, aEvent, aWindow)
Synthesize a wheel event without flush layout at a particular point in aWindow.
- aEvent is an object which may contain the properties:
shiftKey, ctrlKey, altKey, metaKey, accessKey, deltaX, deltaY, deltaZ, deltaMode, lineOrPageDeltaX, lineOrPageDeltaY, isMomentum, isNoLineOrPageDelta, isCustomizedByPrefs, expectedOverflowDeltaX, expectedOverflowDeltaY
deltaMode must be defined, others are ok even if undefined.
expectedOverflowDeltaX and expectedOverflowDeltaY take integer value. The value is just checked as 0 or positive or negative.
aWindow is optional, and defaults to the current window object.
- sendWheelAndPaint(aTarget, aOffsetX, aOffsetY, aEvent, aCallback, aWindow)
This is a wrapper around synthesizeWheel that waits for the wheel event to be dispatched and for the subsequent layout/paints to be flushed.
This requires including paint_listener.js. Tests must call DOMWindowUtils.restoreNormalRefresh() before finishing, if they use this function.
If no callback is provided, the caller is assumed to have its own method of determining scroll completion and the refresh driver is not automatically restored.
- sendWheelAndPaintNoFlush(aTarget, aOffsetX, aOffsetY, aEvent, aCallback, aWindow)
Similar to sendWheelAndPaint but without flushing layout for obtaining
aTarget
position inaWindow
before sending the wheel event.aOffsetX
andaOffsetY
should be offsets against aWindow.
Keyboard input
- sendKey(aKey, aWindow)
Send the non-character key aKey to the focused node. The name of the key should be the part that comes after
DOM_VK_
in the KeyEvent constant name for this key. No modifiers are handled at this point.
- EventUtils.sendChar(aChar, aWindow)
Send the char aChar to the focused element. This method handles casing of chars (sends the right charcode, and sends a shift key for uppercase chars). No other modifiers are handled at this point.
For now this method only works for ASCII characters and emulates the shift key state on US keyboard layout.
- sendString(aStr, aWindow)
Send the string aStr to the focused element.
For now this method only works for ASCII characters and emulates the shift key state on US keyboard layout.
- EventUtils.synthesizeKey(aKey, aEvent, aWindow, aCallback)
accelKey
,altKey
,altGraphKey
,ctrlKey
,capsLockKey
,fnKey
,fnLockKey
,numLockKey
,metaKey
,scrollLockKey
,shiftKey
,symbolKey
,symbolLockKey
Basically, you shouldn’t use these attributes. nsITextInputProcessor manages modifier key state when you synthesize modifier key events. However, if some of these attributes are true, this function activates the modifiers only during dispatching the key events. Note that if some of these values are false, they are ignored (i.e., not inactivated with this function).- Arguments:
aKey (String) – Should be either: - key value (recommended). If you specify a non-printable key name, prepend the
KEY_
prefix. Otherwise, specifying a printable key, the key value should be specified. - keyCode name starting withVK_
(e.g.,VK_RETURN
). This is available only for compatibility with legacy API. Don’t use this with new tests.aEvent (Object) – Optional event object with more specifics about the key event to synthesize.
aEvent.code (String) – If you don’t specify this explicitly, it’ll be guessed from aKey of US keyboard layout. Note that this value may be different between browsers. For example, “Insert” is never set only on macOS since actual key operation won’t cause this code value. In such case, the value becomes empty string. If you need to emulate non-US keyboard layout or virtual keyboard which doesn’t emulate hardware key input, you should set this value to empty string explicitly.
aEvent.repeat (Number) – If you emulate auto-repeat, you should set the count of repeat. This method will automatically synthesize keydown (and keypress).
aEvent.location (*) – If you want to specify this, you can specify this explicitly. However, if you don’t specify this value, it will be computed from code value.
aEvent.type (String) – Basically, you shouldn’t specify this. Then, this function will synthesize keydown (, keypress) and keyup. If keydown is specified, this only fires keydown (and keypress if it should be fired). If keyup is specified, this only fires keyup.
aEvent.keyCode (Number) – Must be 0 - 255 (0xFF). If this is specified explicitly, .keyCode value is initialized with this value.
aWindow (Window) – Is optional and defaults to the current window object.
aCallback (function) – Is optional and can be used to receive notifications from TIP.
- synthesizeNativeKey(aKeyboardLayout, aNativeKeyCode, aModifiers, aChars, aUnmodifiedChars, aCallback)
synthesizeNativeKey() dispatches native key event on active window. This is implemented only on Windows and Mac. Note that this function dispatches the key event asynchronously and returns immediately. If a callback function is provided, the callback will be called upon completion of the key dispatch.
- Arguments:
aKeyboardLayout – One of KEYBOARD_LAYOUT_* defined above.
aNativeKeyCode – A native keycode value defined in NativeKeyCodes.js.
aModifiers – Modifier keys. If no modifire key is pressed, this must be . Otherwise, one or more items referred in _parseNativeModifiers() must be true.
aChars – Specify characters which should be generated by the key event.
aUnmodifiedChars – Specify characters of unmodified (except Shift) aChar value.
aCallback – If provided, this callback will be invoked once the native keys have been processed by Gecko. Will never be called if this function returns false.
- Returns:
True if this function succeed dispatching native key event. Otherwise, false.
- synthesizeKeyExpectEvent(key, aEvent, aExpectedTarget, aExpectedEvent, aTestName, aWindow)
Similar to synthesizeKey except that a test is performed to see if an event is fired at the right target as a result.
aExpectedTarget - the expected originalTarget of the event. aExpectedEvent - the expected type of the event, such as ‘select’. aTestName - the test name when outputing results
To test that an event is not fired, use an expected type preceded by an exclamation mark, such as ‘!select’.
aWindow is optional, and defaults to the current window object.
Drag and drop
- synthesizeDragOver(aSrcElement, aDestElement, aDragData, aDropEffect="move", aWindow=window, aDestWindow=aWindow, aDragEvent={})
Emulate a event sequence of dragstart, dragenter, and dragover.
- Arguments:
aSrcElement (Element) – The element to use to start the drag.
aDestElement (Element) – The element to fire the dragover, dragenter events
aDragData (Array) – The data to supply for the data transfer. This data is in the format: [ [ {“type”: value, “data”: value }, …, ], … ] Pass null to avoid modifying dataTransfer.
aDropEffect (String) – The drop effect to set during the dragstart event, or ‘move’ if omitted.
aWindow (Window) – The window in which the drag happens. Defaults to the window in which EventUtils.js is loaded.
aDestWindow (Window) – Used when aDestElement is in a different window than aSrcElement. Default is to match
aWindow
.aDragEvent (Object) – Defaults to empty object. Overwrites an object passed to sendDragEvent.
- Returns:
Array – A two element array, where the first element is the value returned from sendDragEvent for dragover event, and the second element is the dataTransfer for the current drag session.
- synthesizeDrop(aSrcElement, aDestElement, aDragData, aDropEffect="move", aWindow=window, aDestWindow=aWindow, aDragEvent={})
Emulate a drag and drop by emulating a dragstart and firing events dragenter, dragover, and drop.
- Arguments:
aSrcElement (Element) – The element to use to start the drag.
aDestElement (Element) – The element to fire the dragover, dragenter events
aDragData (Array) – The data to supply for the data transfer. This data is in the format: [ [ {“type”: value, “data”: value }, …, ], … ] Pass null to avoid modifying dataTransfer.
aDropEffect (String) – The drop effect to set during the dragstart event, or ‘move’ if omitted..
aWindow (Window) – The window in which the drag happens. Defaults to the window in which EventUtils.js is loaded.
aDestWindow (Window) – Used when aDestElement is in a different window than aSrcElement. Default is to match
aWindow
.aDragEvent (Object) – Defaults to empty object. Overwrites an object passed to sendDragEvent.
- Returns:
String – The drop effect that was desired.
- synthesizeDropAfterDragOver(aResult, aDataTransfer, aDestElement, aDestWindow=window, aDragEvent={})
Emulate the drop event and mouseup event. This should be called after synthesizeDragOver.
- Arguments:
aResult (*) – The first element of the array returned from
synthesizeDragOver
.aDataTransfer (DataTransfer) – The second element of the array returned from
synthesizeDragOver
.aDestElement (Element) – The element on which to fire the drop event.
aDestWindow (Window) – The window in which the drop happens. Defaults to the window in which EventUtils.js is loaded.
aDragEvent (Object) – Defaults to empty object. Overwrites an object passed to sendDragEvent.
- Returns:
String – “none” if aResult is true,
aDataTransfer.dropEffect
otherwise.
- synthesizePlainDragAndDrop(aParams)
Emulate a drag and drop by emulating a dragstart by mousedown and mousemove, and firing events dragenter, dragover, drop, and dragend. This does not modify dataTransfer and tries to emulate the plain drag and drop as much as possible, compared to synthesizeDrop. Note that if synthesized dragstart is canceled, this throws an exception because in such case, Gecko does not start drag session.
- Arguments:
aParams (Object)
aParams.dragEvent (Event) – The DnD events will be generated with modifiers specified with this.
aParams.srcElement (Element) – The element to start dragging. If srcSelection is set, this is computed for element at focus node.
aParams.srcSelection (Selection|nil) – The selection to start to drag, set null if srcElement is set.
aParams.destElement (Element|nil) – The element to drop on. Pass null to emulate a drop on an invalid target.
aParams.srcX (Number) – The initial x coordinate inside srcElement or ignored if srcSelection is set.
aParams.srcY (Number) – The initial y coordinate inside srcElement or ignored if srcSelection is set.
aParams.stepX (Number) – The x-axis step for mousemove inside srcElement
aParams.stepY (Number) – The y-axis step for mousemove inside srcElement
aParams.finalX (Number) – The final x coordinate inside srcElement
aParams.finalY (Number) – The final x coordinate inside srcElement
aParams.id (Any) – The pointer event id
aParams.srcWindow (Window) – The window for dispatching event on srcElement, defaults to the current window object.
aParams.destWindow (Window) – The window for dispatching event on destElement, defaults to the current window object.
aParams.expectCancelDragStart (Boolean) – Set to true if the test cancels “dragstart”
aParams.expectSrcElementDisconnected (Boolean) – Set to true if srcElement will be disconnected and “dragend” event won’t be fired.
aParams.logFunc (function) – Set function which takes one argument if you need to log rect of target. E.g., console.log.
- synthesizePlainDragAndCancel(aParams, aExpectedDataTransferItems)
synthesizePlainDragAndCancel() synthesizes drag start with synthesizePlainDragAndDrop(), but always cancel it with preventing default of “dragstart”. Additionally, this checks whether the dataTransfer of “dragstart” event has only expected items.
- Arguments:
aParams (Object) – The params which is set to the argument of
synthesizePlainDragAndDrop()
.aExpectedDataTransferItems (eqTest) – All expected dataTransfer items. This data is in the format: [ [ {“type”: value, “data”: value, eqTest: function} …, ], … ] This can also be null. You can optionally provide
eqTest
if the comparison to the expected data transfer items can’t be done with x == y;
- Returns:
boolean – true if aExpectedDataTransferItems matches with DragEvent.dataTransfer of “dragstart” event. Otherwise, the dataTransfer object (may be null) or thrown exception, NOT false. Therefore, you shouldn’t use.
- sendDragEvent(aEvent, aTarget, aWindow)
Send a drag event to the node aTarget (aTarget can be an id, or an actual node) . The “event” passed in to aEvent is just a JavaScript object with the properties set that the real drag event object should have. This includes the type of the drag event.