Action APIs

Sahi's Action APIs simulate user actions on the browser.
Normally Sahi tries to perform actions via Javascript events. This allows play back without the browser being in focus. In rare cases where Javascript events do not work properly, we switch to native events.

Mouse Events

Mouse events simulate the user's mouse based actions. Mouse events are normally triggered at 0,0 coordinates of that element (top left) Events can be forced to perform at other coordinates by using the _xy API.

_xy

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.537.0.17.0.07.5.0

Available for modes: Browser | Windows | Java | iOS

_xy($element, $x, $y)

Arguments
$elementHTML DOM element Element within which we want to perform the mouse action
$xinteger x co-ordinate in pixels
$yinteger y co-ordinate in pixels

Returns
HTML DOM element

Details

Specifies the coordinates on element where the event should be fired.

Eg. _click(_xy(_button("id"), 10, 20)) clicks inside the button, 10px from the left and 20 pixels from the top.

Negative values can be given to specify offset from right and bottom. Eg. _click(_xy(_button("id"), -5, -10)) clicks inside the button, 5px from the right and 10px from the bottom.


Combo keys are available with some mouse events to simulate SHIFT click, CTRL click etc. These are used for multi-selecting on some UIs.

_click

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.07.5.0

Available for modes: Browser | Windows | Java | Android | iOS

_click($element[, $combo])

Arguments
$elementHTML DOM element element to click on
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" This argument is applicable only for Browser mode

Returns
null

Details

_click simulates a user's click on the given element.
_click(_button("Click Me"));
_click(_button("Click Me"), "CTRL"); // clicks with CTRL key pressed
_click(_button("Click Me"), "CTRL|SHIFT"); // clicks with CTRL and SHIFT keys pressed

// With _xy
_click(_xy(_button("Click Me"),4,5)); // Click at coordinates 4,5 pixels inside the button


_doubleClick

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.07.5.0

Available for modes: Browser | Windows | Java | iOS

_doubleClick($element[, $combo])

Arguments
$elementHTML DOM element element to double click on
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" This argument is applicable only for Browser mode

Returns
null

Details

_doubleClick simulates a user's click on the given element.
_doubleClick(_button("DblClick Me"));
_doubleClick(_button("DblClick Me"), "CTRL"); // double clicks with CTRL key pressed
_doubleClick(_button("DblClick Me"), "CTRL|SHIFT"); // double clicks with CTRL and SHIFT keys pressed

// With _xy
_doubleClick(_xy(_button("DblClick Me"),4,5)); // double click at coordinates 4,5 pixels inside the button


_rightClick

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Windows | Java

_rightClick($element[, $combo])

Arguments
$elementHTML DOM element element to right click on
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" This argument is applicable only for Browser mode

Returns
null

Details

_rightClick simulates a user's click on the given element.
_rightClick(_button("Right Click Me"));
_rightClick(_button("Right Click Me"), "CTRL"); // right clicks with CTRL key pressed
_rightClick(_button("Right Click Me"), "CTRL|SHIFT"); // right clicks with CTRL and SHIFT keys pressed

// With _xy
_rightClick(_xy(_button("Right Click Me"),4,5)); // right click at coordinates 4,5 pixels inside the button
warning _rightClick will not bring up the browser's context menu.


_mouseDown

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.537.0.17.0.0NA

Available for modes: Browser | Windows | Java

_mouseDown($element[, $isRight[, $combo]])

Arguments
$elementHTML DOM element element to perform mouse down on
$isRightboolean optionalSet to true for a left-hand mouse, default false
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" This argument is applicable only for Browser mode

Returns
null

Details

_mouseDown simulates a mousedown on the given element.
_mouseDown(_button("Mouse Down"));
_mouseDown(_button("Mouse Down"), true); //mouseDown for a left-hand mouse
_mouseDown(_button("Mouse Down"), false, "CTRL"); //mouseDown with CTRL key pressed
_mouseDown(_button("Mouse Down"), false, "CTRL|SHIFT"); //mouseDown with CTRL and SHIFT keys pressed


_mouseUp

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.537.0.17.0.0NA

Available for modes: Browser | Windows | Java

_mouseUp($element[, $isRight[, $combo]])

Arguments
$elementHTML DOM element element to perform mouse up on
$isRightboolean optionalSet to true for a left-hand mouse, default false
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" This argument is applicable only for Browser mode

Returns
null

Details

simulates a mouseup on the given element.
_mouseup(_button("Mouse up"));
 _mouseup(_button("Mouse up"), true); // mouseup for a left-hand mouse
_mouseup(_button("Mouse up"), false, "CTRL"); // mouseup with CTRL key pressed
_mouseup(_button("Mouse up"), false, "CTRL|SHIFT"); // mouseup with CTRL and SHIFT keys pressed


_mouseOver

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Windows | Java

_mouseOver($element[, $combo])

Arguments
$elementHTML DOM element element to perform hover over or move the mouse over.
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" This argument is applicable only for Browser mode

Returns
null

Details

_mouseOver simulates mouse hovering on the given element.
_mouseOver(_button("Click Me"));
_mouseOver(_button("Click Me"), "CTRL"); // mouseOver with CTRL key pressed
_mouseOver(_button("Click Me"), "CTRL|SHIFT"); // mouseOver with CTRL and SHIFT keys pressed


_check

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Windows | Java

_check($checkBoxOrRadioElement)

Arguments
$checkBoxOrRadioElementHTML DOM element The check box or Radio element to check

Returns
null

Details

Checks the given checkbox or radio element. If already checked, this API does not do anything.


_uncheck

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.537.0.17.0.0NA

Available for modes: Browser | Windows | Java

_uncheck($checkBoxElement)

Arguments
$checkBoxElementHTML DOM element The check box to uncheck

Returns
null

Details

Unchecks the given checkbox. If already unchecked, this API does not do anything.


_setSelected

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Windows | Java

_setSelected($element, $optionToSelect[, $isMultiple])

Arguments
$elementHTML DOM element Select dropdown
$optionToSelectstring|integer|array of strings|array of integers Option's text, id or index; can also pass an array of options for multi-select
$isMultipleboolean optionalset isMultiple true for multiselect

Returns
null

Details

Selects one or more elements in a select dropdown.
_setSelected(_select("Age"), "28"); // Selects the option visible as "28" in a select box
_setSelected(_select("color"), 1);  // Selects the second option in a select box
_setSelected(_select("color"), "red");         // Selects red in a multiselect box
_setSelected(_select("color"), "blue", true);  // Selects blue also in the multiselect box
_setSelected(_select("color"), ["red", "blue"]); // Unselects previous and selects red and blue in a multiselect box
_setSelected(_select("color"), [1,2,3]); // Unselects previous and selects the second, third and fourth options in a multiselect box
_setSelected(_select("color"), ["green", "yellow"], true); // Keeps previous options selected and selects "green" and "yellow" also


_dragDrop

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.5.07.5.0

Available for modes: Browser | Windows | Android | iOS

_dragDrop($dragElement, $dropElement[, $windowName])

Arguments
$dragElementHTML DOM element Element to be dragged
$dropElementHTML DOM element Element on which the dragged element will be dropped
$windowNamestring optional Target window for dropped element (available only for Windows mode)

Returns
null

Details

Simulates a drag and drop action
// Drag the item and drop it in the shopping cart
_dragDrop(_image("item"), _byId("ShoppingCart"));
// Drag the item and drop it at coordinates 20,40 pixels inside shopping cart
_dragDrop(_image("item"), _xy(_byId("ShoppingCart"), 20, 40));

// Examples for Windows mode

//Drag and Drop actions will be performed on same window.
_selectWindow("Source Window");
_dragDrop(_image("item.jpg"), _listitem("images"));
//Drag and Drop actions will be performed on different windows.
_selectWindow("Source Window");
_dragDrop(_image("item.jpg"), _listitem("images"), "Destination Window");


_dragDropXY

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.1NA7.5.0

Available for modes: Browser | Android | iOS

_dragDropXY($dragElement, $x, $y[, $isRelative])

Arguments
$dragElementHTML DOM element Element to be dragged
$xinteger x coordinate of drop point on the page
$yinteger y coordinate of drop point on the page
$isRelativeboolean optional Specifies whether the coordinates are relative to current position of draggable element.

Returns
null

Details

_dragDropXY simulates a drag and drop action. It drags the element and drops it at the given x, y coordinate.
// If _image("item") is located at coordinates (50, 150)

// Drag the item and drop it at the coordinate (100, 300)
// The end result is that the element's coordinates will be at (100, 300)
_dragDropXY(_image("item"),  100, 300);

// Drag the item and drop it at the coordinate (50+100, 150+300)
// The end result is that the element's coordinates will be at (150, 450)
_dragDropXY(_image("item"),  100, 300, true);


Touch Events

_tap

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.0NANANA7.5.0

Available for modes: Browser | iOS

_tap($element[, $count])

Arguments
$elementHTML DOM element HTML form element that needs to be tapped
$countinteger optionalnumber of times the element needs to be tapped. Default value is 1.

Returns
null

Details

Simulates a tap event(touch event) on the HTML element

_touch

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.0NANANANA

Available for modes: Browser

_touch($element[, $count])

Arguments
$elementHTML DOM element HTML form element on which we need to fire a touch event
$countinteger optionalnumber of times the element needs to be touched. Default value is 1.

Returns
null

Details

Simulates a touch event on the HTML element

_touchStart

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.0NANANANA

Available for modes: Browser

_touchStart($element)

Arguments
$elementHTML DOM element HTML form element on which we need to fire a touch start event

Returns
null

Details

Simulates a touch start event on the HTML element

_touchEnd

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.0NANANANA

Available for modes: Browser

_touchEnd($element)

Arguments
$elementHTML DOM element HTML form element on which we need to fire a touch end event

Returns
null

Details

Simulates a touch end event on the HTML element

_touchCancel

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.0NANANANA

Available for modes: Browser

_touchCancel($element)

Arguments
$elementHTML DOM element HTML form element on which we need to cancel the ongoing touch event

Returns
null

Details

Simulates a touch cancel event on the HTML element

_touchMove

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.0NANANANA

Available for modes: Browser

_touchMove($element, $moveX, $moveY[, $isRelative])

Arguments
$elementHTML DOM element HTML form element which we need to move/drag.
$moveXinteger number of pixels the element needs to move in x-direction
$moveYinteger number of pixels the element needs to move in y-direction
$isRelativeboolean optionalif true, the element will move relative to the current location of the element.if false, element will move to the position where the horizontal coordinate and vertical coordinate are 'moveX' and 'moveY'. Default value is true.

Returns
null

Details

Simulates a touch move event on the HTML element

_swipe

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.0NANANANA

Available for modes: Browser

_swipe($element, $moveX, $moveY, $isRelative)

Arguments
$elementHTML DOM element HTML form element on which we need to simulate swipe event.
$moveXinteger number of pixels the element needs to move in x-direction
$moveYinteger number of pixels the element needs to move in y-direction
$isRelativeboolean if true, the element will move relative to the current location of the element. If false, element will move to the position where clientX and clientY are moveX and moveY.

Returns
null

Details

Simulates a touch move event on the HTML element


Keyboard Events

_setValue

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.07.5.0

Available for modes: Browser | Windows | Java | Android | iOS

_setValue($element, $value)

Arguments
$elementHTML DOM element HTML form element whose value is to be set
$valuestring Value to be set

Returns
null

Details

Simulates text entry into html form elements (textbox like elements and textareas) The sequence of events performed are Focus Enter Text Remove focus
// populates textbox identified as _textbox("user") with Ram
_setValue(_textbox("user"), "Ram");

_keyDown

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Java

_keyDown($element, $charInfo[, $combo])

Arguments
$elementHTML DOM element Any HTML element
$charInfocharacter|integer|pr_KC charInfo can be:
  • a character (eg. 'b')
  • charCode of a character (eg. 98)
  • an array of [keyCode, charCode] (eg. [13,13] for pressing ENTER key)
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"

Returns
null

Details

Simulates pressing down a key on the given element.
_keyDown(document.body, 'a');
_keyDown(document.body, 98);
_keyDown(document.body, [13,13]);
_keyDown(document.body, 'a', "CTRL");

_keyUp

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Java

_keyUp($element, $charInfo[, $combo])

Arguments
$elementHTML DOM element Any HTML element
$charInfocharacter|integer|pr_KC charInfo can be:
  • a character (eg. 'b')
  • charCode of a character (eg. 98)
  • an array of [keyCode, charCode] (eg. [13,13] for pressing ENTER key)
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"

Returns
null

Details

Simulates releasing a key press on the given element.
_keyUp(document.body, 'a');
_keyUp(document.body, 98);
_keyUp(document.body, [13,13]);
_keyUp(document.body, 'a', "CTRL");

_keyPress

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Java

_keyPress($element, $charInfo[, $combo])

Arguments
$elementHTML DOM element Any HTML element
$charInfocharacter|integer|array of integers charInfo can be:
  • a character (eg. 'b')
  • charCode of a character (eg. 98)
  • an array of [keyCode, charCode] (eg. [13,13] for pressing ENTER key)
$combostring optionalAny combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"

Returns
null

Details

Simulates pressing a key on the given element. Does keyDown and keyUp together.
_keyPress(document.body, 'a');
_keyPress(document.body, 98);
_keyPress(document.body, [13,13]);
_keyPress(document.body, 'a', "CTRL");

_type

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Windows | Java

_type($element, $text)

Arguments
$elementHTML DOM element element in which the text is to be typed
$textstring text to be typed

Returns
null

Details

Types the text into the element. Different from _setValue. _type does not bring or remove focus from element.
_type(_textbox("user"), "am");

_setPassword

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
7.5.0NA7.0.17.5.07.5.0

Available for modes: Browser | Windows | Java | Android | iOS

_setPassword($element, $text)

Arguments
$elementHTML DOM element element in which the password is to be typed
$textstring encrypted password to be typed

Returns
null

Details

Types the password into the element. Different from _setValue. For encrypting the password use _encrypt or use password encoder from editor.
_setPassword(_password("password"), "MgkKEQBU");


Focus Events

_focus

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.0NA

Available for modes: Browser | Windows | Java

_focus($element)

Arguments
$elementHTML DOM element Any HTML element to focus on

Returns
null

Details

Brings focus to given element.
_focus(_textbox("username"));


_removeFocus

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.537.0.17.0.0NA

Available for modes: Browser | Windows | Java

_removeFocus($element)

Arguments
$elementHTML DOM element Any HTML element to remove focus from

Returns
null

Details

Similar to clicking somewhere else on the window to remove focus from given element. Forces onblur events to be called. Blur happens automatically during Sahi's script execution. This API is rarely used explicitly. Same as _blur.
_removeFocus(_textbox("username"));


_blur

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.537.0.1NANA

Available for modes: Browser

_blur($element)

Arguments
$elementHTML DOM element Any HTML element to remove focus from

Returns
null

Details

Similar to clicking somewhere else on the window to remove focus from given element. Forces onblur events to be called. Blur happens automatically during Sahi's script execution. This API is rarely used explicitly. Same as _removeFocus.
_blur(_textbox("username"));


Text Selection

Selecting text for manipulation (like selecting text in a Rich Text Editor to change font to bold)

_selectRange

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.05.07.0.17.0.0NA

Available for modes: Browser | Windows | Java

_selectRange($element, $rangeStart, $rangeEnd)

Arguments
$elementHTML DOM element element to select on
$rangeStartinteger start position of selection
$rangeEndinteger end position of selection

Returns
null

Details

Example:
// If the text was "abcdefghij"
_selectRange(_rte(1), 2, 4); // selects text cd
var $text = _getSelectionText(); // $text = "cd"

_selectRange(_rte(1), 2, 2); // places the cursor at 3rd position without any selection


_selectTextRange

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.1.05.07.0.17.0.0NA

Available for modes: Browser | Windows | Java

_selectTextRange($element, $searchText[, $position])

Arguments
$elementHTML DOM element element to select on
$searchTextstring text to search for and select. The text can be a pure string or a regular expression with an index
$positionstring optionalcan be "before" or "after". if specified, the selection moves to the start or end of searchText.

Returns
null

Details

Example:
//Given a sample string
//This bright red apple is sweeter than that dull red apple

_selectTextRange(_rte(1), "red apple"); // selects the first red apple
_selectTextRange(_rte(1), "red apple[1]"); // selects the second red apple
_selectTextRange(_rte(1), "/ap.le/[1]"); // selects the second apple
var $text = _getSelectionText(); // $text = "apple"
_selectTextRange(_rte(1), "/ap.le/[1]", "before"); // moves the cursor before the second apple, with no selection
_selectTextRange(_rte(1), "/ap.le/[1]", "after"); // moves the cursor after the second apple, with no selection


Page Navigation

_navigateTo

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.1NANA

Available for modes: Browser

_navigateTo($url[, $forceReload])

Arguments
$urlstring URL to navigate to. Can be relative to current page.
$forceReloadboolean optional If the current page URL is same as url, Sahi will not reload the page by default. Set to true to force reload when urls are same.

Returns
null

Details

_navigateTo loads the given url in the top frame of the window. To load in a popupWindow, use _selectWindow to select that window first.

// If current page is not http://sahi.co.in/demo/
_navigateTo("http://sahi.co.in/demo/"); // Will navigate to this page.

// If current page is itself "http://sahi.co.in/demo/"
_navigateTo("http://sahi.co.in/demo/"); // will do nothing
_navigateTo("http://sahi.co.in/demo/", true); // Will force navigation to this page.

_selectWindow("popWin");
_navigateTo("http://sahi.co.in/demo/"); // loads in the popup window.
info To force reload of the current page without knowing the URL, you may use
_call(top.location.reload()); // reload via Javascript
// or
_windowAction("refresh"); // native event

Waits

_wait

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.17.0.07.5.0

Available for modes: Browser | Windows | Java | Android | iOS

_wait($timeout[, $condition])

Arguments
$timeoutinteger time in milliseconds to wait for
$conditionSahi expression optional condition to wait for. If specified, _wait will return if either the condition is met or if the time elapsed has exceeded timeout, whichever comes first.

Returns
null

Details

Forces script to wait for given time or given condition to be true, which ever comes first
_wait(1000); // Will stop execution for a second

// Wait till div by id "ajaxConfirm" is populated for max 5 seconds.
_wait(5000, _getText(_div("ajaxConfirm"))!="");

// Wait till button becomes visible
_wait(5000, _isVisible(_button("Confirm")));

// Wait till "Loading ..." message disappears
_wait(1000); // may take a second before that message appears.
_wait(5000, !_isVisible(_div("Loading ..."))); // wait max 5 seconds for it to disappear.


Native Events

In rare cases where Javascript events do not work properly, we switch to native events. These events are created by the underlying Operating System. The browser needs to be in focus for this to work properly. These APIs only work if the browser and Sahi's proxy are on the same system. So these APIs are not available on mobile devices. Some native events may not work on all platforms.
For native events, the window and element SHOULD be in focus. Use _focusWindow() before using native events in a script. When using suites, do one of these
  • isolate all scripts with native events into its own suite, and run that suite using 1 thread only.
  • OR Use _lock and _unlock in scripts where contention for window focus is possible.

_typeNative

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.0NANANANA

Available for modes: Browser

_typeNative($text)

Arguments
$textstring Text to type

Returns
null

Details

Types the text using native events
_focus(_textbox("user"));
_focusWindow();
_typeNative("Ram");


_typeKeyCodeNative

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.0NANA7.0.0NA

Available for modes: Browser | Windows | Java

_typeKeyCodeNative($keyCode)

Arguments
$keyCodeinteger Key Code of keyboard key to be pressed.

Returns
null

Details

Presses the keyboard key for given keyCode java.awt.event.KeyEvent defines keyCodes as constants which can be passed to this function. Users can type even those characters which might not be present on a keyboard's primary layer (characters which can be typed without using any key combinations) but has an ASCII code associated with them.

The user need to define the character in Sahi/userdata/config/keyCode_combinations.txt file in following format:

"VK_keyCode constant":"ASCII Code" Example:- "VK_DOLLAR":"36"
_focusWindow();
_setValue(_textbox("search"), "coffee");
_typeKeyCodeNative(java.awt.event.KeyEvent.VK_ENTER); // Press enter key
_typeKeyCodeNative(java.awt.event.KeyEvent.VK_DOLLAR); // Press dollar key defined in keyCode_combinations.txt file


_focusWindow

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
4.3NANA7.5.0NA

Available for modes: Browser | Windows | Java

_focusWindow()

Arguments
None

Returns
null

Details

Brings the window above all other windows. It is generally needed before using other native events or before taking screen shots Works only on Windows Operating Systems currently. On Mac and Linux, does nothing. For popup windows, use _selectWindow first.
_focusWindow(); // bring window into focus.
_takeScreenShot();

// For popup windows, use _selectWindow first
_selectWindow("popWin"); // target further statements at popWin window
_focusWindow(); // bring popup window into focus.
_takeScreenShot();


_windowAction

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.0NANA7.5.0NA

Available for modes: Browser | Windows | Java

_windowAction($action[, $width[, $height]])

Arguments
$actionstring Action can be one of
  • "focus"
  • "maximize"
  • "minimize"
  • "restore"
  • "refresh"
  • "resize"
$widthinteger optional Specifies the width of the browser window while using the 'resize' option.
$heightinteger optional Specifies the height of the browser window while using the 'resize' option.

Returns
null

Details

Performs various window level actions. Current works only on Windows Operating Systems. On Mac and Linux does nothing. For popup windows, use _selectWindow first.
_windowAction("focus"); // focus window. Same as _focusWindw
_windowAction("maximize"); // mazimize window.
_windowAction("minimize"); // minimize window.
_windowAction("restore"); // restore window.
_windowAction("refresh"); // refresh window.
_windowAction("resize",500,300); // resize the window with the given width and height.

// maximizing a popup window
_selectWindow("popWin"); // first select the popWin window to target further steps on.
_windowAction("maximize");
To set delay for a window action API, please do the following
  • Search and edit the following section in sahi.properties[SAHI_INSTALL_PATH\config\sahi.properties]
window_action_api.wait_after_unique_title_set=300 // waits for 300ms after unique title set.
window_action_api.wait_before_title_revert=200 // waits for 200ms before unique title revert.
window_action_api.wait_after_unique_title_revert=500 // waits for 500ms after unique title revert.


_clickNative

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
6.0.0NANA7.0.07.5.0

Available for modes: Browser | Java | Android | iOS

_clickNative($element[, $combo[, $isRight[, $isDouble]]])

Arguments
$elementHTML DOM element Element that has to be clicked.
$combostring optional Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"
$isRightboolean optional If true, the click is a right click
$isDoubleboolean optionalIf true, the click is a double click

Returns
null

Details

Simulates a native click event on the element.
warningBefore calling this API, we need to call _focusWindow to bring the window into focus.
_clickNative(_button("b1"));
info This API is very useful when _click does not help or a native click cannot be simulated by focusing on the element and generating a Space or Enter key (_typeKeyCodeNative(java.awt.event.KeyEvent.VK_SPACE)).

One can use this to click on File elements to bring up the File chooser dialog, when _setFile and _setFile2 do not work.


_rightClickNative

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
6.0.0NANA7.0.0NA

Available for modes: Browser | Java

_rightClickNative($element[, $combo])

Arguments
$elementHTML DOM element element that has to be clicked.
$combostring optional Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"

Returns
null

Details

Simulates a native right click event on the element.
warningBefore calling this API, we need to call _focusWindow to bring the window into focus.
_rightClickNative(_button("b1"));


_doubleClickNative

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
6.0.0NANA7.0.0NA

Available for modes: Browser | Java

_doubleClickNative($element[, $combo])

Arguments
$elementHTML DOM element element that has to be double clicked.
$combostring optional Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"

Returns
null

Details

Simulates a native double click event on the element.
warningBefore calling this API, we need to call _focusWindow to bring the window into focus.
_doubleClickNative(_button("b1"));


_clickNativeXY

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
6.0.0NANA7.5.07.5.0

Available for modes: Browser | Java | Android | iOS

_clickNativeXY($x, $y[, $combo[, $isRight[, $isDouble]]])

Arguments
$xinteger x coordinate of the screen position to be clicked
$yinteger y coordinate of the screen position to be clicked
$combostring optional Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"
$isRightboolean optional If true, the click is a right click
$isDoubleboolean optionalIf true, the click is a double click

Returns
null

Details

Simulates a click event at the point (x,y).
warningBefore calling this API, we need to call _focusWindow to bring the window into focus.
_clickNativeXY(100, 200);
_clickNativeXY(150,300, "ALT"); // ALT + click


_mouseOverNative

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
6.0.1NANANANA

Available for modes: Browser

_mouseOverNative($element[, $combo])

Arguments
$elementHTML DOM element Element to perform hover over or move the mouse over.
$combostring optional Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT"

Returns
null

Details

Simulates a native mouse over event on the element.
warningBefore calling this API, we need to call _focusWindow to bring the window into focus.
_mouseOverNative(_button("b1"));


_dragDropNative

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
6.0.0NANA7.5.07.5.0

Available for modes: Browser | Java | Android | iOS

_dragDropNative($el, $el2)

Arguments
$elHTML DOM element the draggable element
$el2HTML DOM element the droppable element

Returns
null

Details

Simulates a dragdrop event from element 1 to element 2 using native events.
warningBefore calling this API, we need to call _focusWindow to bring the window into focus.
_dragDropNative(_div("draggable"), _div("droppable"));
info This API is useful when _dragDrop does not help. Example: When you need to drag an element from one iframe into a drop target in another iframe, you would use _dragDropNative.


_dragDropNativeXY

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
6.0.0NANANA7.5.0

Available for modes: Browser | Android | iOS

_dragDropNativeXY($x1, $y1, $x2, $y2)

Arguments
$x1integer x coordinate of the draggable element
$y1integer y coordinate of the draggable element
$x2integer x coordinate of the droppable element
$y2integer y coordinate of the droppable element

Returns
null

Details

Simulates a dragdrop event from element at first set of coordinates to element at second set of coordinates, using native events.
warningBefore calling this API, we need to call _focusWindow to bring the window into focus.
_dragDropNativeXY(100,50, 100,150);


File Upload

File upload can be done via two _setFile APIs (_setFile, _setFile2) or via native file upload. We recommend using the _setFile APIs because they do not require the browser to be in focus and hence are more stable. _setFile2 is recommended since its triggers the events bind to element as well as handles file validations.

_setFile

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.1NANA

Available for modes: Browser

_setFile($element, $filePath[, $actionURL])

Arguments
$elementHTML DOM element HTML Form File Element whose value needs to be set
$filePathstring Path of the file to be uploaded.
$actionURLstring optional The form action URL to which the file is submitted. This is an optional parameter. Use it in cases where the form's action URL is changed on setting the file. By default, it uses the form's current action URL.

Returns
null

Details

_setFile(_file("id"), "C:\\abc\\efg.jpg");
_setFile(_file("id"), "C:\\abc\\efg.jpg", "formSubmit.jsp");
warning Note that _setFile works in a round about way. It is not handled at the browser level. It is handled at the proxy. So you will not see the file input box being populated with your desired filename. But when the form is submitted, the proxy will add the correct file to the request before it sends it to your web server. But if there are javascript checks before form submit to see if the filename is non-empty, then the script will not work as desired.
info If there are javascript validations on the file field, use _setFile2 which works in the same way, but requires substitution of readonly property so that validations may pass.


_setFile2

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
4.54.37.0.1NANA

Available for modes: Browser

_setFile2($element, $filePath[, $actionURL[, $isMultipartRequest[, $isFileValidation]]])

Arguments
$elementHTML DOM element HTML Form File Element whose value needs to be set
$filePathstring Path of the file to be uploaded.
$actionURLstring optional The form action URL to which the file is submitted. This is an optional parameter. Use it in cases where the form's action URL is changed on setting the file. By default, it uses the form's current action URL.
$isMultipartRequestboolean optional Set to false when file element is not part of form. Default value is true.
$isFileValidationboolean optional Set to true when there are client side validations on file or when file element is not part of form. Default value is false.

Returns
null

Details

    infoNOTE: $isMultipartRequest and $isFileValidation are added since Sahi Pro: 7.5.0. For old document Refer here
///when file element is part of HTML Form and there are no validations on File.
_setFile2(_file("id"), "C:\\abc\\efg.jpg");
//when the HTML Form's action URL is changed on setting the file
_setFile2(_file("id"), "C:\\abc\\efg.jpg", "formSubmit.jsp");
warning
//when file element is not part of HTML Form and there are client side validations on File.
_setFile2(_file("id"), "C:\\abc\\efg.jpg", "formSubmit.jsp", false, true);
//when file element is part of HTML Form and there are client side validations on File.
_setFile2(_file("id"), "C:\\abc\\efg.jpg", "formSubmit.jsp", true, true);
Configuration changes are needed before running the script when there are validations on file. Please follow instructions below for configuration changes:
  1. Go to ConfigureUI Page -> substitutions.xml
  2. Uncomment below lines in substitutions.xml by replacing it outside of --> symbol:
    <rule>
    	<name>fileUpload</name>
    	<urlPattern>.*JsFileNameHandlingFileValidation.*</urlPattern>
    	<isRegExp>true</isRegExp>
    	<find><![CDATA[\.files(?![a-zA-Z].*)]]></find>
    	<replace><![CDATA[._file]]></replace>
    </rule>
  3. Replace JsFileNameHandlingFileValidation in above rule with the name of the javascript file where the client side validation code resides. (Contact support if you are unsure)
  4. Save substitutions.xml.
  5. Restart Sahi and Play the Script.
info If you use relative paths in _setFile and _setFile2, they should be relative to userdata folder. Either use the correct relative path or the full absolute path.

Troubleshooting

  1. Look to see if there are any exceptions on the Sahi console (the command prompt). If it shows any FileNotFoundException, correct the path of your file.
  2. Check if the URL to which the form is being submitted is correct. Sometimes the URL is changed when the form is submitted, and Sahi needs to be told about it using the 3rd parameter in _setFile/setFile2

Identifying action url for _setFile/_setFile2

  1. Launch a browser from the Sahi Dashboard.
  2. Perform the file upload functionality in your app manually.
  3. Check the output on the Sahi server console. It will look something like this.
    [java] FileUpload: Multipart Request Found
    [java] Action URL for upload:
    [java] http://localhost/demo/php/fileUpload.php
    [java] The above action URL may be required as the third parameter while
    [java] calling _setFile and _setFile2 APIs.
    [java] Recording: false
    [java] For troubleshooting, click on 'Enable Traffic Logs' link on the Sahi Dashboard
    [java] and perform the upload operation. Upload logs will be created in
    [java] sahi/userdata/logs/file_upload/ folder.


    As you can see from the output, http://localhost/demo/php/fileUpload.php is the action url in this case.
  4. Once you have identified the action url, use that as the third parameter in _setFile/_setFile2.
info Complete examples on _setFile and _setFile2 are available in sahi/userdata/scripts/demo/fileUpload.sah It can be run with start URL http://sahi.co.in/demo/

File upload using native events

Sometimes file uploads with the previous method may fail. In such cases we resort to native events.
function setFileUpload($fileEl, $path) {
	_focusWindow();
	_wait(1000); // needed
	// focus on the element
	_focus($fileEl);
	// click "space" to bring up the browser dialog
	_typeKeyCodeNative(java.awt.event.KeyEvent.VK_SPACE);
	_wait(1000);
	// type the file path
	_typeNative($path);
	_wait(1000);
	// press enter
	_typeKeyCodeNative(java.awt.event.KeyEvent.VK_ENTER);
	_wait(1000);
}
// Then invoke it like this:
setFileUpload(_file("id"), "C:\\abc\\efg.jpg");
//or
setFileUpload(_file("id"), _resolvePath("uploadme.txt")); // resolves relative to this file
warning _focusWindow is available since Sahi Pro V4.3. It works only on Windows currently.

File Download

File download overview

Sahi's proxy detects file downloads, and automatically saves them to sahi/userdata/temp/download directory. Sahi also adds the sessionId to the file name, so that multiple simultaneous tests do not overwrite each others files. So if you were clicking on a "download" link which downloads a "setup.exe" file, this is how Sahi will handle it.
  1. Click on "download" link
  2. Sahi detects that it is a downloadable file, based on its MimeType and Content-Disposition headers. It then downloads and saves the file into sahi/userdata/temp/download/ after renaming it to something like: sahi_0384a26207e6104f5f08868032bd170de76d__setup.exe
  3. Once the file is downloaded Sahi exposes the original name of the file ("setup.exe") through the API: _lastDownloadedFileName()
  4. Another API, _saveDownloadedAs, allows the file to be renamed and copied over to a convenient directory for you to work on.
  5. API: _clearLastDownloadedFileName() clears out the _lastDownloadedFileName() so that further files can be downloaded and worked upon.

_lastDownloadedFileName

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.52NANANA

Available for modes: Browser

_lastDownloadedFileName()

Arguments
None

Returns
stringName of the last downloaded file

Details

Returns the last downloaded file name.


_saveDownloadedAs

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.52NANANA

Available for modes: Browser

_saveDownloadedAs($path)

Arguments
$pathstring File path to copy this file into. Needs to be a file path not a directory. If path is relative, it is resolved relative to userdata directory.

Returns
null

Details

Renames/copies the file into specified directory for further processing.


_clearLastDownloadedFileName

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.52NANANA

Available for modes: Browser

_clearLastDownloadedFileName()

Arguments
None

Returns
null

Details

Clears out the _lastDownloadedFileName() so that further files can be downloaded and worked upon


File download APIs example

_assertNull(_lastDownloadedFileName()); // nothing so far
_click(_link("download")); // click on download link
// Wait for a while till _lastDownloadedFileName() becomes NOT null. This is when the download is complete.
// We wait for a maximum of 90 seconds or till _lastDownloadedFileName() becomes NOT null.
// If you find that your file is huge and takes much longer, run the following statement in a loop for 5 or 6 retries.
// Do NOT increase 90000 to more than 120000.
_wait(90000, _lastDownloadedFileName() != null);
// Assert the name of the downloaded file.
_assertEqual("setup.exe", _lastDownloadedFileName()); // check if downloaded

if (_lastDownloadedFileName() != null) {
	_saveDownloadedAs("c:/myownpath/setup.exe"); // save to another path
	_clearLastDownloadedFileName(); // clear the variable
	_assertNull(_lastDownloadedFileName()); // check to see if cleared.
}


File download troubleshooting

info Sahi detects that a file is to be downloaded, based on
  1. its content type (configurable via sahi/userdata/config/download_contenttypes.txt)
  2. The Content-Disposition: attachment header
  3. Whether the URL is configured in sahi/userdata/config/download_urls.txt
If you see a file download dialog during playback, do the following:
  1. Check if the download URL follows a specific pattern. If yes, add the pattern of the URL to download_urls.txt Eg., if your download url is http://mysite.example.com/export_doc.jsp?id=12318812, add
    .*export_doc[.]jsp.*
    to sahi/userdata/config/download_urls.txt
  2. If there are multiple files that are to be downloaded, and they all are of a particular content-type, add the content type to sahi/userdata/config/download_contenttypes.txt
  3. If your file download response always has content-disposition as "attachment", you can tell sahi to download them by default by setting
    download.download_if_contentdisposition_is_attachment=true
    in sahi/userdata/config/userdata.properties. This is the default since Sahi Pro 4.3.2

Handling file downloads triggered in a new window

Sometimes a webpage may open a new window to show a PDF file. In this case, we need to ask Sahi to send a HTML response back using _sendHTMLResponseAfterFileDownload API (need Sahi Pro V4.2+).

_sendHTMLResponseAfterFileDownload

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
4.34.3NANANA

Available for modes: Browser

_sendHTMLResponseAfterFileDownload($enable)

Arguments
$enableboolean true enables html response behaviour, false disables html response

Returns
null

Details

Forces Sahi to send back an HTML response after file download. Useful when file opens/downloads in a new window.

Add
_sendHTMLResponseAfterFileDownload(true);
before the statement which triggers the download and Sahi will send back an HTML response. To turn it off, call
_sendHTMLResponseAfterFileDownload(false);


Use it like this:
_assertNull(_lastDownloadedFileName()); // nothing so far
_sendHTMLResponseAfterFileDownload(true);

_click(_link("Show PDF in new Window"));
_wait(90000, _lastDownloadedFileName() != null);
_assertEqual("test.pdf", _lastDownloadedFileName());

if (_lastDownloadedFileName() != null) {
	_saveDownloadedAs("c:/test.pdf");
	_clearLastDownloadedFileName(); // clear the variable
	_assertNull(_lastDownloadedFileName()); // check to see if cleared.
}
// Close the popup window
_selectWindow("/File Downloaded/");
_click(_link("Close Window"));

// Select back the main window
_selectWindow();

_sendHTMLResponseAfterFileDownload(false);


info Technical Explanation When the browser navigates to a downloadable file, Sahi automatically downloads the file. After the file has downloaded Sahi sends a 204 response which essentially asks the page to stay where it is. Now if that original page has Sahi's code in it, the Sahi script will proceed normally. If it does not, then the script will stop. Since the PDF window is a fresh window, there is no content in it and Sahi's script stops.

File download from a different domain

When a file is downloaded from a different domain than the invoking page, the file will get downloaded to userdata\temp\download folder successfully. But since the download is from a different domain, it is not associated with the current script session. Hence _lastDownloadedFileName() will return null and so _saveDownloadedAs() will fail. To solve this problem, add _addToSession("http://newdomain") in the script before triggering download.

_addToSession

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
4.5NANANANA

Available for modes: Browser

_addToSession($domain)

Arguments
$domainstring Domain to be associated with the current script session

Returns
null

Details

Adds the domain to the current script session.

Example:
_addToSession("http://downloaddomain.com"); // Here the download url is http. Change downloaddomain.com to your domain.
_addToSession("https://downloaddomain.com"); // Here the download url is https. Change downloaddomain.com to your domain.
danger NOTE: If it is a https url, it is a MUST to prefix the domain name with "https://".
// Add new domain url to Sahi's playback session
_addToSession("http://downloads.mydomain.com");
// NOTE _addToSession comes before click
_click(_link("Download"));
// The rest of the code is same as above...


Once we add _addToSession, _lastDownloadedFileName() will return the correct downloaded file name, and hence _saveDownloadedAs() will work correctly.

Window open/close APIs

_closeWindow

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.53NA7.5.0NA

Available for modes: Browser | Windows | Java

_closeWindow()

Arguments
None

Returns
null

Details

Closes the current window. This will work only for popups. Eg.
_popup("popWin")._closeWindow();

_closeBrowser

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
4.3.2NANANANA

Available for modes: Browser

_closeBrowser()

Arguments
None

Returns
null

Details

Closes the browsers in this session in the middle of a script.
warning Use with caution.
  1. This can be only used when singleSession is false in a suite.
  2. ALWAYS follow this with _openBrowser()or _launchNewBrowser(). Otherwise the script will hang.
  3. If multiple browsers is opened, then first use _selectBrowser() with browser id. Otherwise last selected browser will close.
  4. There should not be any statement present between _selectBrowser and _closeBrowser, this will allow the browser to close properly.
  5. A wait(5000) may be needed after closing to allow the browser to clean up properly.

_openBrowser

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
4.3.2NA7.0.1NANA

Available for modes: Browser

_openBrowser()

Arguments
None

Returns
null

Details

Opens the browser in this session in the middle of a script. Used to reopen browser after _closeBrowser.
warningUse with caution.
  1. This can be only used when singleSession is false in a suite.
  2. Always use it after a _closeBrowser() command
  3. This will not allow multiple browsers in the same session. Use _launchNewBrowser and _selectBrowser for that

_openWindow

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
5.0NA7.0.1NANA

Available for modes: Browser

_openWindow([$url[, $name[, $size]]])

Arguments
$urlstring optional URL of the page to open. If no URL is specified, a new window with "about:blank" is opened.
$namestring optional name of the window.
$sizearray of integers optional height and width of the window.

Returns
null

Details

Opens a new browser window.
_openWindow("http://sahitest.com/demo/training/login.htm","defaultSahiPopup",[1280,600]);


Calling Generic Code

_call

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.1NANA

Available for modes: Browser

_call($expression)

Arguments
$expressionexpression Any expression which needs to be evaluated on the browser Note that the expression is not quoted and is NOT a string.

Returns
stringThe completion value of evaluating the given code. If the completion value is empty, undefined is returned.

Details

_call is a generic API to bypass Sahi's action APIs and directly call javascript on the DOM.
// For example, a date field may bring up the calendar, but selecting the year,month etc. may be time consuming.
// For repeated flows, one may want to bypass this by directly setting the value of the field through javascript.
_call(_textbox("date").value = "25/02/1990");

var $a=_call(2 + 2);
_log($a);// returns 4


_eval

Since: Sahi ProSahi OSSahi Pro StarterDesktop Add-OnMobile Add-On
3.527.0.1NANA

Available for modes: Browser

_eval($evalString)

Arguments
$evalStringstring Any string which needs to be javascript 'eval'ed on the browser

Returns
stringThe completion value of evaluating the given code. If the completion value is empty, undefined is returned.

Details

_eval, like _call, is a generic API to bypass Sahi's action APIs and directly call javascript on the DOM. However, _eval takes a string instead of an expression.
// For example, a date field may bring up the calendar, but selecting the year,month etc. may be time consuming.
// For repeated flows, one may want to bypass this by directly setting the value of the field through javascript.
_eval("_textbox(\"date\").value = \"25/02/1990\"");

var $a=_eval('2 + 2');
_log($a);// returns 4
warning_call is recommended over _eval since _call is easier to use.