# Action Functions

Sahi's Action functions simulate user actions on the application screen.

Normally Sahi tries to perform actions by trigerring events on the application. This approach lets tests run without the application window being in focus.

## Mouse Events

Mouse events simulate the user's mouse based actions.

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 Pro 3.5, Desktop Engine 7.0.0, Mobile Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, Android, iOS, SAP

```js
_click($element[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to click on |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT"<br>This argument is applicable only for Browser mode |

Returns: `null`

\_click simulates a user's click on the given element.

```js
_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 Pro 3.5, Desktop Engine 7.0.0, Mobile Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, iOS, Android(9.0.0), SAP

```js
_doubleClick($element[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to double click on |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT"<br>This argument is applicable only for Browser mode |

Returns: `null`

\_doubleClick simulates a user's click on the given element.

```js
_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 Pro 3.5, Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

```js
_rightClick($element[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to right click on |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT"<br>This argument is applicable only for Browser mode |

Returns: `null`

\_rightClick simulates a user's click on the given element.

```js
_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
```

:::caution[Important]
\_rightClick will not bring up the browser's context menu.
:::

### _mouseDown

Since: Sahi Pro 3.5, Desktop Engine 7.0.0

Modes: Browser, Windows, Java

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to perform mouse down on |
| `$isRight` | boolean (optional) | Set to true for a left-hand mouse, default **false** |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT"<br>This argument is applicable only for Browser mode |

Returns: `null`

\_mouseDown simulates a mousedown on the given element.

```js
_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 Pro 3.5, Desktop Engine 7.0.0

Modes: Browser, Windows, Java

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to perform mouse up on |
| `$isRight` | boolean (optional) | Set to true for a left-hand mouse, default **false** |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT"<br>This argument is applicable only for Browser mode |

Returns: `null`

simulates a mouseup on the given element.

```js
_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 Pro 3.5, Desktop Engine 7.0.0

Modes: Browser, Windows, Java

```js
_mouseOver($element[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to perform hover over or move the mouse over. |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT"<br>This argument is applicable only for Browser mode |

Returns: `null`

\_mouseOver simulates mouse hovering on the given element.

```js
_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 Pro 3.5, Desktop Engine 7.0.0, Mobile Engine 8.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, Android, iOS, SAP

```js
_check($checkBoxOrRadioElement[, $checked])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$checkBoxOrRadioElement` | HTML DOM element | The check box or Radio element to check or uncheck. |
| `$checked` | boolean (optional) | Set to false to uncheck the checkbox. Default value is true. This is available since Sahi Pro v11.0.0.8. |

Returns: `null`

Checks or unchecks the given checkbox or checks radio element.

### _uncheck

Since: Sahi Pro 3.5, Desktop Engine 7.0.0, Mobile Engine 8.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, Android, iOS, SAP

```js
_uncheck($checkBoxElement)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$checkBoxElement` | HTML DOM element | The check box to uncheck |

Returns: `null`

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

### _setSelected

Since: Sahi Pro 3.5, Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Select dropdown |
| `$optionToSelect` | string\|integer\|array of strings\|array of integers | Option's text, id or index;<br>can also pass an array of options for multi-select<br>Only option's text can be passed for SAP mode |
| `$isMultiple` | boolean (optional) | set isMultiple true for multiselect<br>This argument is not available for SAP mode |

Returns: `null`

Selects one or more elements in a select dropdown.

```js
_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
```

### _setValueFromList

Since: Sahi Pro 9.2.0

Modes: Browser

```js
_setValueFromList($element, $inputData[, $optionToSelect])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Input element |
| `$inputData` | string\|array of strings | Data to filter (case-insensitive). |
| `$optionToSelect` | string\|integer\|array of strings\|array of integers (optional) | Option's text, id or index; The text can be a pure string or a regular expression with an index<br>can also pass an array of options for multi-select.<br>Note- Array of options can only work with email input type element on other browsers than firefox. |

Returns: `null`

Selects one or more elements from the datalist or simulates text entry into input elements for $inputData(Data to filter).

```js
_setValueFromList(_textbox("Age"), "28", 0); // Selects the first option visible after writing "28" from the list.
_setValueFromList(_textbox("Shirt"), "large", "/red/"); // Selects the first option matches with red after writing "large" from the list.
_setValueFromList(_textbox("Shirt"), "large"); // Populates textbox identified as _textbox("Shirt") with "large".
// Below code selects both of the first email ids visible after writing "green" and "yellow" from the list(if browser is other than firefox).
_setValueFromList(_email("color"), ["green", "yellow"], [0, 0]);
```

### _expand

Since: Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Windows, Java, SAP

```js
_expand($element[, $identifier])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | Windows\|Java\|SAP element | Tree element to be expanded |
| `$identifier` | string (optional) | Identifier of tree node. -   For SAP mode, this identifier must be hierarchical path of the tree node. -   Identifier is not optional for SAP mode |

Returns: `null`

Expands the tree node.

```js
// For windows applications
_expand(_treeviewitem("First"));

// For Java applications
_expand(_jvJTree("First"), "Root"); //If tree is passed as an argument, pass visible text of tree node.
_expand(_jvJTreeItem(_jvJTree("First"), "Root")); //If tree item passed as an argument, then no need to pass visible text of tree node.

// For SAP mode
_expand(_tree("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell"), "SAP menu/Accounting/Document Verification");
_expand(_tree("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell"), "SAP menu/Logistics/Shipment Order"));
```

### _collapse

Since: Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Windows, Java, SAP

```js
_collapse($element[, $identifier])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | Windows\|Java\|SAP element | Tree element to be collapsed |
| `$identifier` | string (optional) | Identifier of tree node. -   For SAP mode, this identifier must be hierarchical path of the tree node. -   Identifier is not optional for SAP mode |

Returns: `null`

Collapses the tree node.

```js
// For windows applications
_collapse(_treeviewitem("First"));

// For Java applications
_collapse(_jvJTree("First"), "Root"); //If tree is passed as an argument, pass visible text of tree node.
_collapse(_jvJTreeItem(_jvJTree("First"), "Root")); //If tree item passed as an argument, then no need to pass visible text of tree node.

// For SAP mode
_collapse(_tree("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell"), "SAP menu/Accounting/Document Verification");
_collapse(_tree("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell"), "SAP menu/Logistics/Shipment Order"));
```

### _dragDrop

Since: Sahi Pro 3.5, Desktop Engine 7.5.0, Mobile Engine 7.5.0

Modes: Browser, Windows, Android, iOS

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

| Argument | Type | Description |
| --- | --- | --- |
| `$dragElement` | HTML DOM element | Element to be dragged |
| `$dropElement` | HTML DOM element | Element on which the dragged element will be dropped |
| `$windowName` | string (optional) | Target window for dropped element (available only for Windows mode) |

Returns: `null`

Simulates a drag and drop action

```js
// 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");
```

:::note
Since v9.2.0, \_dragDrop function automatically scrolls the page while finding the drag element and drop element. To disable this behavior, set `sahi.browser.dragdrop.disable_scrolling` to true in `userdata.properties`.
:::

:::note
Since v9.1.0, \_dragdrop function drags from the center of draggable and drops at the center of droppable. To revert this behavior, `sahi.browser.dragdrop.top_left` property is available since v9.1.2 in `userdata.properties`. Set its value to true for dragging from the top left of draggable to drop at the top left of droppable as in versions prior to v9.1.0.
:::

### _dragDropXY

Since: Sahi Pro 3.5, Mobile Engine 7.5.0

Modes: Browser, Android, iOS

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

| Argument | Type | Description |
| --- | --- | --- |
| `$dragElement` | HTML DOM element | Element to be dragged |
| `$x` | integer | x coordinate of drop point on the page |
| `$y` | integer | y coordinate of drop point on the page |
| `$isRelative` | boolean (optional) | Specifies whether the coordinates are relative to current position of draggable element. |

Returns: `null`

\_dragDropXY simulates a drag and drop action. It drags the element and drops it at the given x, y coordinate.

```js
// 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);
```

### _dropFile

Since: Sahi Pro 8.1.0

Modes: Browser

```js
_dropFile($filePath, $dropElement)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$filePath` | string | Path of the file to be uploaded. |
| `$dropElement` | HTML DOM element | Element on which file will be dropped. |

Returns: `null`

\_dropFile simulates file drop. It drops file on specified element.

```js
// drop file in the shopping cart element
_dropFile("D:/image.jpg", _byId("ShoppingCart"));
// drop file in gallery element
_dropFile("D:/sun.jpg", _div("gallery"));
```

### _xy

Since: Sahi Pro 3.5, Desktop Engine 7.0.0, Mobile Engine 7.5.0

Modes: Browser, Windows, Java, iOS

```js
_xy($element, $x, $y)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Element within which we want to perform the mouse action |
| `$x` | integer | x co-ordinate in pixels |
| `$y` | integer | y co-ordinate in pixels |

Returns: `HTML DOM element`

Mouse Event based functions like \_click, \_doubleClick, \_rightClick, etc. are normally triggered at 0,0 coordinates of that element (top left). This function can be used to specify other coordinates on element where the event should be fired.

```js
_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.
_click(_xy(_button("id"), -5, -10)) // Clicks inside the button, 5px from the right and 10px from the bottom.
```

## Touch Events

### _tap

Since: Sahi Pro 5.1.0, Mobile Engine 7.5.0

Modes: Browser, iOS

```js
_tap($element[, $count])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element that needs to be tapped |
| `$count` | integer (optional) | number of times the element needs to be tapped. Default value is **1**. |

Returns: `null`

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

### _touch

Since: Sahi Pro 5.1.0

Modes: Browser

```js
_touch($element[, $count])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element on which we need to fire a touch event |
| `$count` | integer (optional) | number of times the element needs to be touched. Default value is **1**. |

Returns: `null`

Simulates a touch event on the HTML element

### _touchStart

Since: Sahi Pro 5.1.0

Modes: Browser

```js
_touchStart($element)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element on which we need to fire a touch start event |

Returns: `null`

Simulates a touch start event on the HTML element

### _touchEnd

Since: Sahi Pro 5.1.0

Modes: Browser

```js
_touchEnd($element)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element on which we need to fire a touch end event |

Returns: `null`

Simulates a touch end event on the HTML element

### _touchCancel

Since: Sahi Pro 5.1.0

Modes: Browser

```js
_touchCancel($element)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element on which we need to cancel the ongoing touch event |

Returns: `null`

Simulates a touch cancel event on the HTML element

### _touchMove

Since: Sahi Pro 5.1.0

Modes: Browser

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element which we need to move/drag. |
| `$moveX` | integer | number of pixels the element needs to move in x-direction |
| `$moveY` | integer | number of pixels the element needs to move in y-direction |
| `$isRelative` | boolean (optional) | if true, the element will move relative to the current location of the element.<br>If false, element will move to the position where the horizontal coordinate and vertical coordinate are 'moveX' and 'moveY'.<br>Default value is **true**. |

Returns: `null`

Simulates a touch move event on the HTML element

### _swipe

Since: Sahi Pro 5.1.0

Modes: Browser

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element on which we need to simulate swipe event. |
| `$moveX` | integer | number of pixels the element needs to move in x-direction |
| `$moveY` | integer | number of pixels the element needs to move in y-direction |
| `$isRelative` | boolean | if true, the element will move relative to the current location of the element.<br>If false, element will move to the position where clientX and clientY are moveX and moveY. |

Returns: `null`

Simulates a touch move event on the HTML element

## Keyboard Events

### _setValue

Since: Sahi Pro 3.5, Desktop Engine 7.0.0, Mobile Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, Android, iOS, SAP

```js
_setValue($element, $value[, $props])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML form element whose value is to be set |
| `$value` | string | Value to be set |
| `$props` | object (optional) | Properties to specify for clearing the textbox, keyboard buttons to hide keyboard (Specific to iOS Automation) and triggering keyboard events (specific to Android Automation). 1. iOSKeyboardButton, string, optional<br>Keyboard button identifier, which is used to dismiss the keyboard. This property is specific to iOS automation. 2. clearTextbox, boolean, optional<br>Default is false. If specified as true, the textbox is cleared by selecting all text and pressing the delete key. This property is specific to iOS automation. 3. triggerKeyEvents, boolean, optional<br>Default is false. If specified as true, keyboard events will be triggerd for the value to be set. This property is specific to Android automation. |

Returns: `null`

Simulates text entry into input elements like textbox, textarea etc.\
The events are performed in the following sequence :

1.  Focus on element
2.  Enter the value to be set
3.  Remove focus from the element

```js
// Populates textbox identified as _textbox("user") with Ram
_setValue(_textbox("user"), "Ram");

// Below example is specific to iOS Automation.
// Clears the texbox first and populates textbox identified as _textbox("user") with Ram and click on the return button of the keyboard.
_setValue(_textbox("user"), "Ram", {"iOSKeyboardButton":"return", "clearTextbox":true});

// Below example is specific to Android Automation.
// Trigger the keyboard events for value to be set
_setValue(_textbox("user"), "Ram", {"triggerKeyEvents":true});
```

:::note
NOTE: Argument `$props` is available since Mobile Engine: 8.0.0. For old document [Refer here](http://sahipro.com/alldocs/v7.5.0/sahi-apis/action-apis.html#_setValue)
:::

:::note
`iOSKeyboardButton` overrides the default keyboard buttons specified by `ios.keyboard.buttons.autoclick` property in `sahi.properties`.
:::

### _keyDown

Since: Sahi Pro 3.5, Desktop Engine 7.0.0

Modes: Browser, Java, Windows (8.0.0)

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Any HTML element |
| `$charInfo` | character\|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) |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT" |

Returns: `null`

Simulates pressing down a key on the given element.

```js
_keyDown(document.body, 'a');
_keyDown(document.body, 98);
_keyDown(document.body, [13,13]);
_keyDown(document.body, 'a', "CTRL");
```

-   :::note
    NOTE: \_keyDown is available for Windows and Flex since Sahi Pro: 8.0.0.
    :::

### _keyUp

Since: Sahi Pro 3.5, Desktop Engine 7.0.0

Modes: Browser, Java, Windows (8.0.0)

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Any HTML element |
| `$charInfo` | character\|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) |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT" |

Returns: `null`

Simulates releasing a key press on the given element.

-   :::note
    NOTE: \_keyUp is available for Windows and Flex since Sahi Pro: 8.0.0. For old document refer [here](http://sahipro.com/alldocs/v7.0.0/sahi-apis/action-apis.html#_keyDown)
    :::

```js
_keyUp(document.body, 'a');
_keyUp(document.body, 98);
_keyUp(document.body, [13,13]);
_keyUp(document.body, 'a', "CTRL");
```

### _keyPress

Since: Sahi Pro 3.5, Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Browser, Java, Windows (8.0.0), SAP

```js
_keyPress($element, $keyInfo[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Element that supports keyPress action |
| `$keyInfo` | character\|integer\|array of integers\|string | keyInfo can be specified as: -   A character (eg. 'b') -   A charCode of a character (eg. 98) -   An array of [keyCode, charCode] (eg. [13,13] for pressing ENTER key) -   As a string (eg. "Ctrl\|S") in SAP mode. |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT"<br>Not applicable for SAP mode |

Returns: `null`

Simulates pressing a key on the given element. Does keyDown and keyUp together.

```js
_keyPress(document.body, 'a');
_keyPress(document.body, 98);
_keyPress(document.body, [13,13]);
_keyPress(document.body, 'a', "CTRL");

// Below samples are for SAP mode
_keyPress(_window("Create Inquiry: Initial Screen"), "Enter");
_keyPress(_window("Create Inquiry: Overview"), "Ctrl|S");
_keyPress(_gridView("wnd[0]/usr/cntlBCALVC_TOOLBAR_D100_C1/shellcont/shell"), "F4");
```

:::note
-   In SAP mode, `_keyPress` accepts argument `$keyInfo` as a string. The specified `$keyInfo` must be one of the following values :\
    `Enter`, `F1`, `F2`, `F3`, `F4`, `F5`, `F6`, `F7`, `F8`, `F9`, `F10`, `Ctrl|S`, `F12`, `Shift|F1`, `Shift|F2`, `Shift|F3`, `Shift|F4`, `Shift|F5`, `Shift|F6`, `Shift|F7`, `Shift|F8`, `Shift|F9`, `Shift|Ctrl|0`, `Shift|F11`, `Shift|F12`, `Ctrl|F1`, `Ctrl|F2`, `Ctrl|F3`, `Ctrl|F4`, `Ctrl|F5`, `Ctrl|F6`, `Ctrl|F7`, `Ctrl|F8`, `Ctrl|F9`, `Ctrl|F10`, `Ctrl|F11`, `Ctrl|F12`, `Ctrl|Shift|F1`, `Ctrl|Shift|F2`, `Ctrl|Shift|F3`, `Ctrl|Shift|F4`, `Ctrl|Shift|F5`, `Ctrl|Shift|F6`, `Ctrl|Shift|F7`, `Ctrl|Shift|F8`, `Ctrl|Shift|F9`, `Ctrl|Shift|F10`, `Ctrl|Shift|F11`, `Ctrl|Shift|F12`, `Ctrl|E`, `Ctrl|F`, `Ctrl|/`, `Ctrl|\` , `Ctrl|N`, `Ctrl|O`, `Ctrl|X`, `Ctrl|C`, `Ctrl|V`, `Ctrl|Z`, `Ctrl|PageUp`, `PageUp`, `PageDown`, `Ctrl|PageDown`, `Ctrl|G`, `Ctrl|R`, `Ctrl|P`
-   In most cases, key press action in SAP mode will have an effect on the entire window. For example, if we press an enter key, all the fields of the window are validated. Thus `_window` or `_popupWindow` element must be passed to `_keyPress` function in such cases.
:::

### _type

Since: Sahi Pro 3.5, Desktop Engine 7.0.0

Modes: Browser, Windows, Java

```js
_type($element, $text)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element in which the text is to be typed |
| `$text` | string | text to be typed |

Returns: `null`

Types the text into the element. Different from \_setValue. \_type does not bring or remove focus from element.

```js
_type(_textbox("user"), "am");
```

### _setPassword

Since: Sahi Pro 7.5.0, Desktop Engine 7.5.0, Mobile Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, Android, iOS, SAP

```js
_setPassword($element, $text[, $isPlainText])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element in which the password is to be typed |
| `$text` | string | encrypted password to be typed |
| `$isPlainText` | boolean (optional) | If true, password is treated as plain text. Default is false. |

Returns: `null`

Types the password into the element. Different from \_setValue. For encrypting the password use [\_encrypt](https://resources.sahipro.com/docs/sahi-script/functions/utilities/#_encrypt) or use [password encoder](https://resources.sahipro.com/docs/using-sahi/sahi-script-editor/#password-encoder) from editor.

```js
_setPassword(_password("password"), "MgkKEQBU");
```

:::note
**Salt** is used to encrypt the password.\
You can change the **salt** by changing the property `script.salt_for_password_encryption` in `userdata/config/userdata.properties`file.
:::

:::note
If `script.salt_for_password_encryption` property is present in `userdata/config/userdata_hidden.properties` as well, then this property will be considered only from `userdata_hidden.properties`file.
:::

## Focus Events

### _focus

Since: Sahi Pro 3.5, Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

```js
_focus($element)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Any HTML element to focus on |

Returns: `null`

Brings focus to given element.

```js
_focus(_textbox("username"));
```

### _removeFocus

Since: Sahi Pro 3.5, Desktop Engine 7.0.0

Modes: Browser, Windows, Java

```js
_removeFocus($element)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Any HTML element to remove focus from |

Returns: `null`

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 function is rarely used explicitly. Same as \_blur.

```js
_removeFocus(_textbox("username"));
```

### _blur

Since: Sahi Pro 3.5

Modes: Browser

```js
_blur($element)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Any HTML element to remove focus from |

Returns: `null`

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 function is rarely used explicitly. Same as \_removeFocus.

```js
_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 Pro 5.1.0, Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

```js
_selectRange($element, $rangeStart, $rangeEnd)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to select on |
| `$rangeStart` | integer | start position of selection |
| `$rangeEnd` | integer | end position of selection |

Returns: `null`

Example:

```js
// 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 Pro 5.1.0, Desktop Engine 7.0.0

Modes: Browser, Windows, Java

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element to select on |
| `$searchText` | string | text to search for and select. The text can be a pure string or a regular expression with an index |
| `$position` | string (optional) | can be "before" or "after". if specified, the selection moves to the start or end of searchText. |

Returns: `null`

Example:

```js
//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 Pro 3.5

Modes: Browser

```js
_navigateTo($url[, $forceReload])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$url` | string | URL to navigate to. Can be relative to current page. |
| `$forceReload` | boolean (optional) | If the current page URL is same as url, Sahi will not reload the page by default.<br>Set to true to force reload when urls are same. |

Returns: `null`

\_navigateTo loads the given url in the top frame of the window. To load in a popup window, first select that window using `_selectWindow` function.

```js
// 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.
```

:::note
To force reload of the current page without knowing the URL, you may use

```js
_call(top.location.reload()); // reload via Javascript
// or
_windowAction("refresh"); // native event
```
:::

## Native Events

In rare cases where Mouse events do not work properly, we switch to native events. These events are created by the underlying Operating System. The application window needs to be in focus for this to work properly.

These functions only work if the application and Sahi are running on the same system. So these functions are not available on mobile devices.

Some native events may not function on all platforms. To simulate native events on macOS, Sahi requires Accessibility permissions. Follow these steps to grant permission:

1.  Open System Settings (or System Preferences on older macOS versions).
2.  Go to Privacy & Security > Accessibility.
3.  Locate the terminal application you use to run Sahi.
4.  Ensure it is checked (enabled).

:::danger[Caution]
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 Pro 5.0, Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

```js
_typeNative($text[, $isEncrypted])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$text` | string | Text to type |
| `$isEncrypted` | boolean (optional) | Set as true if the text is encrypted |

Returns: `null`

Types the text using native events

```js
_focus(_textbox("user"));
_focusWindow();
_typeNative("Ram");
_focus(_password("password"));
_typeNative("MgkKEQBU", true)
```

:::note
-   For encrypting the password use [\_encrypt](https://resources.sahipro.com/docs/sahi-script/functions/utilities/#_encrypt) or use [password encoder](https://resources.sahipro.com/docs/using-sahi/sahi-script-editor/#password-encoder) from editor.
-   **Salt** is used to encrypt the password. You can change the **salt** by changing the property `script.salt_for_password_encryption` in `userdata/config/userdata.properties`file.
-   If `script.salt_for_password_encryption` property is present in `userdata/config/userdata_hidden.properties` as well, then this property will be considered only from `userdata_hidden.properties`file.
:::

### _keyPressNative

Since: Sahi Pro 11.2.0, Desktop Engine 11.2.0, SAP Engine 11.2.0

Modes: Browser, Windows, Java, SAP

```js
_keyPressNative($key[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$key` | string | Key to be pressed, e.g. "a", "F4", "ENTER", "+", "7". |
| `$combo` | string (optional) | Any combo key such as "CTRL", "SHIFT", "ALT", "WINDOWS" or "META".<br>Can also be two or more keys together like "CTRL\|SHIFT", "CTRL\|ALT\|SHIFT". |

Returns: `null`

Presses the specified keyboard key.

Every keyboard comes with a standard layer, and a shift layer. The standard layer usually contains lowercase letters and numbers, while the shift layer contains capital letters and symbols. Keys on the shift layer can be passed directly to this function. They can also be simulated using a combination key. For example, to press '@', you can directly pass '@' as key to this function. You can also pass '2' as key and 'SHIFT' as combo key to press '@' with U.S keyboard layout.

```js
_focusWindow();
_setValue(_textbox("search"), "coffee");
_keyPressNative("ENTER"); // Press enter key

_keyPressNative("F4", "ALT"); // Presses Alt+F4
_keyPressNative("t", "CTRL|SHIFT"); // Presses Ctrl+Shift+t
_keyPressNative("0", "CTRL"); // Presses Ctrl+0
```

### _typeKeyCodeNative

Since: Sahi Pro 5.0, Desktop Engine 7.0.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

```js
_typeKeyCodeNative($keyCode)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$keyCode` | integer | Key Code of keyboard key to be pressed. |

Returns: `null`

Presses the keyboard key for given keyCode

:::note
function [\_keyPressNative](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_keypressnative) should be preferred over `_typeKeyCodeNative`.
:::

[java.awt.event.KeyEvent](https://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html) 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"

```js
_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 Pro 4.3, Desktop Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

```js
_focusWindow()
```

| Argument | Type | Description |
| --- | --- | --- |
| `None` |  |  |

Returns: `null`

Brings the window above all other windows.\
It is generally needed before using other native events or before taking screen shots\
For popup windows, use `_selectWindow` first.

```js
_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();
```

:::note
`_focusWindow` works only on Windows and Linux operating systems. It does not work on Mac.
:::

:::note
For`_focusWindow` to work on Linux, xdotool must be installed. If xdotool is not installed, kindly install it using appropriate package dependency manager like `apt-get` or `yum` or any other tool respective to the Linux distribution.
:::

### _windowAction

Since: Sahi Pro 5.0, Desktop Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

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

| Argument | Type | Description |
| --- | --- | --- |
| `$action` | string | Action can be one of -   "focus" -   "maximize" -   "minimize" -   "restore" -   "refresh" -   "resize" |
| `$width` | integer (optional) | Specifies the width of the browser window while using the 'resize' option. |
| `$height` | integer (optional) | Specifies the height of the browser window while using the 'resize' option. |

Returns: `null`

Performs various window level actions.\
For popup windows, use `_selectWindow` first.

```js
_windowAction("focus"); // focus window. Same as _focusWindw
_windowAction("maximize"); // maximize 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 function, do the following

-   Search and edit the following section in _sahi.properties_`[SAHI_INSTALL_PATH\config\sahi.properties]`

```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.
```

:::note
`_windowAction` works only on Windows and Linux operating systems. It does not work on Mac.
:::

:::note
For`_windowAction` to work on Linux, xdotool must be installed. If xdotool is not installed, kindly install it using appropriate package dependency manager like `apt-get` or `yum` or any other tool respective to the Linux distribution.
:::

### _clickNative

Since: Sahi Pro 6.0.0, Desktop Engine 7.0.0, Mobile Engine 7.5.0, Visual Assist Engine 10.0.0

Modes: Browser, Java, Android, iOS, Windows(11.0.0)

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

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Element that has to be clicked. |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT" |
| `$isRight` | boolean (optional) | If true, the click is a right click |
| `$isDouble` | boolean (optional) | If true, the click is a double click |

Returns: `null`

Simulates a native click event on the element.

:::caution[Important]
Before calling this function, we need to call `_focusWindow` to bring the window into focus.
:::

```js
_clickNative(_button("b1"));
```

:::note
This function is very useful when [\_click](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_click) does not help or a native click cannot be simulated by focusing on the element and generating a Space or Enter key ([\_typeKeyCodeNative](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_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 Pro 6.0.0, Desktop Engine 7.0.0, Visual Assist Engine 10.0.0

Modes: Browser, Java, Windows(11.0.0)

```js
_rightClickNative($element[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element that has to be clicked. |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT" |

Returns: `null`

Simulates a native right click event on the element.

:::caution[Important]
Before calling this function, we need to call `_focusWindow` to bring the window into focus.
:::

```js
_rightClickNative(_button("b1"));
```

### _doubleClickNative

Since: Sahi Pro 6.0.0, Desktop Engine 7.0.0, Mobile Engine 11.1.0, Visual Assist Engine 10.0.0

Modes: Browser, Java, Windows(11.0.0), Android

```js
_doubleClickNative($element[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | element that has to be double clicked. |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT" |

Returns: `null`

Simulates a native double click event on the element.

:::caution[Important]
Before calling this function, we need to call `_focusWindow` to bring the window into focus.
:::

```js
_doubleClickNative(_button("b1"));
```

### _clickNativeXY

Since: Sahi Pro 6.0.0, Desktop Engine 7.5.0, Mobile Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Java, Android, iOS, SAP, Windows

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

| Argument | Type | Description |
| --- | --- | --- |
| `$x` | integer | x coordinate of the screen position to be clicked |
| `$y` | integer | y coordinate of the screen position to be clicked |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT" |
| `$isRight` | boolean (optional) | If true, the click is a right click |
| `$isDouble` | boolean (optional) | If true, the click is a double click |

Returns: `null`

Simulates a click event at the point (x,y).

:::caution[Important]
Before calling this function, we need to call `_focusWindow` to bring the window into focus.
:::

```js
_clickNativeXY(100, 200);
_clickNativeXY(150,300, "ALT"); // ALT + click
```

### _mouseOverNative

Since: Sahi Pro 6.0.1, Desktop Engine 11.0.0, Visual Assist Engine 10.0.0

Modes: Browser, Windows(11.0.0)

```js
_mouseOverNative($element[, $combo])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | Element to perform hover over or move the mouse over. |
| `$combo` | string (optional) | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META";<br>Can also be two or more keys together like "CTRL\|SHIFT" |

Returns: `null`

Simulates a native mouse over event on the element.

:::caution[Important]
Before calling this function, we need to call `_focusWindow` to bring the window into focus.
:::

```js
_mouseOverNative(_button("b1"));
```

### _dragDropNative

Since: Sahi Pro 6.0.0, Desktop Engine 7.5.0, Mobile Engine 7.5.0

Modes: Browser, Java, Android, iOS, Windows

```js
_dragDropNative($el, $el2)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$el` | HTML DOM element | the draggable element |
| `$el2` | HTML DOM element | the droppable element |

Returns: `null`

Simulates a dragdrop event from element 1 to element 2 using native events.

:::caution[Important]
Before calling this function, we need to call `_focusWindow` to bring the window into focus.
:::

```js
_dragDropNative(_div("draggable"), _div("droppable"));
```

:::note
This function is useful when [\_dragDrop](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_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 Pro 6.0.0, Desktop Engine 7.0.0, Mobile Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Java, Android, iOS, SAP, Windows

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

| Argument | Type | Description |
| --- | --- | --- |
| `$x1` | integer | x coordinate of the draggable element |
| `$y1` | integer | y coordinate of the draggable element |
| `$x2` | integer | x coordinate of the droppable element |
| `$y2` | integer | y coordinate of the droppable element |

Returns: `null`

Simulates a dragdrop event from element at first set of coordinates to element at second set of coordinates, using native events.

:::caution[Important]
Before calling this function, we need to call `_focusWindow` to bring the window into focus.
:::

```js
_dragDropNativeXY(100,50, 100,150);
```

## File Upload

<iframe width="560" height="315" src="https://www.youtube.com/embed/PP_9iZGze2s?si=buVh9zPQk0p2BtWC" title="Learn to upload files using Sahi Pro" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen></iframe>

File upload can be done using the three functions `_setFile3`, `_setFile2`, `_setFile`. File upload can also be done using [Native Events](https://resources.sahipro.com/docs/sahi-script/functions/actions/#native-events), provided the browser is in the foreground. The three functions `_setFile3`, `_setFile2`, `_setFile` do not require the browser to be in the foreground and hence are more stable than the Native Events.

There may be client-side validations for the HTML File element in your application. So it may require certain javascript events to be triggered during file upload.\
function `_setFile3` triggers the necessary javascript events on the HTML File element. It correctly handles client-side validations and does not require substitution as needed for function `_setFile2`. Thus function `_setFile3` is recommended for file upload.

### _setFile3

Since: Sahi Pro 9.0.0

Modes: Browser

```js
_setFile3($element, $filePaths[, $actionURL[, $fileElement]])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML File Element that triggers the popup window for file upload. There is a special case in which another clickable HTML element needs to be passed instead of file element. This Special Case is described in details.. |
| `$filePaths` | string\|array of strings | Path of the files to be uploaded. A file path can be absolute as well as relative. When relative, the file path is resolved relative to the current script file path. |
| `$actionURL` | string (optional) | The form action URL to which the file is submitted. This is an optional parameter.<br>Use it in cases where the form's action URL is changed on setting the file.<br>By default, it uses the form's current action URL. |
| `$fileElement` | HTML DOM element (optional) | HTML File Element. Needed only for a special case when another clickable HTML element is passed as 1st parameter instead of file element. This Special Case is described in details. This is available since Sahi Pro v9.2.1. |

Returns: `null`

function `_setFile3` performs file upload operation.

:::caution[Important]
Due to security reasons, browsers restrict reading the file path being uploaded. Consequently, during recording, the parameter `$filePaths` will not be captured correctly. It needs to be updated with the correct file path(s) after recording.
:::

:::caution[Important]
Using the recorder will record `_setFile3` with appropriate arguments except for special case described below.

**Special Case** :

In few applications, popup window for file upload is triggered after clicking on a clickable HTML element like button. Also, after clicking on this HTML element, the HTML File element is removed from the HTML page.

In such cases, a step `_click($clickableElement);` will be recorded. But function `_setFile3` will not be recorded. To fix this, modify the recorded script as below.

1.  Replace `_click($clickableElement);` with `_setFile3($clickableElement, $filePaths);`. Run the script to verify.
2.  If file upload fails. it implies that function `_setFile3` was not able to automatically find the correct HTML File element. So, follow the instructions below to find correct HTML File element.
    1.  Replace the step `_setFile3($clickableElement, $filePaths);` with below debugging steps.

        `// Use below steps to debug and find the new HTML File element`\
        `var $fileElements = _collectElementsInfo("_file");`\
        `for (var $i=0; $i < $fileElements.length; $i++) {`\
             `var $fileElementIdentifier = $fileElements[$i]["identifiers"]["name"];`\
             `_setFile3($clickableElement, $filePaths, null, $fileElementIdentifier);`\
             `_log("File element identifier - " + $fileElementIdentifier);`\
             `//assertion for file upload`\
        `}`
    2.  Run the script. Open the Logs. Note down the identifier of the HTML File element for which file upload assertion passed.
    3.  Replace the debugging steps added earlier with a single step `_setFile3($clickableElement, $filePaths, null, _file($fileElementIdentifier));`.
:::

```js
_setFile3(_file("id"), "data.csv");
_setFile3(_span("upload"), "details.xlsx");
_setFile3(_span("upload"), "profile.pdf", null, _file("id"));
_setFile3(_file("id"), ["C:/abc/efg.jpg", "C:/abc/abc.png"]);
//when the HTML Form's action URL is changed on setting the file
_setFile3(_file("id"), "C:/abc/efg.jpg", "formSubmit.jsp");
_setFile3(_file("id"), ["C:/abc/efg.jpg", "C:/abc/abc.png"], "formSubmit.jsp");
```

:::caution[Important]
Note that \_setFile3 does not support IE versions below 11. So use [\_setFile2](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_setfile2) for IE versions below 11.
:::

### _setFile2

Since: Sahi Pro 4.5

Modes: Browser

```js
_setFile2($element, $filePaths[, $actionURL[, $isMultipartRequest[, $isFileValidation]]])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML File Element whose value needs to be set. |
| `$filePaths` | string\|array of strings | Path of the files to be uploaded. File path is resolved relative to current script file. |
| `$actionURL` | string (optional) | The form action URL to which the file is submitted. This is an optional parameter.<br>Use it in cases where the form's action URL is changed on setting the file.<br>By default, it uses the form's current action URL. |
| `$isMultipartRequest` | boolean (optional) | Set to false when file element is not part of form. Default value is **true**. |
| `$isFileValidation` | boolean (optional) | Set to true when there are client side validations on file or when file element is not part of form.<br>Default value is **false**. |

Returns: `null`

:::caution[Important]
[`_setFile3`](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_setfile3) is recommended since it does not require substitution.
:::

:::note
NOTE: $isMultipartRequest and $isFileValidation are available since Sahi Pro: 7.5.0. For old document [Refer here](http://sahipro.com/alldocs/v7.0.1/sahi-apis/action-apis.html#_setFile2)
:::

```js
///when file element is part of HTML Form and there are no client side validations on File.
_setFile2(_file("id"), "data.csv");
_setFile2(_file("id"), ["C:/abc/efg.jpg","C:/abc/abc.png"]);
//when the HTML Form's action URL is changed on setting the file
_setFile2(_file("id"), "C:/abc/efg.jpg", "formSubmit.jsp");
_setFile2(_file("id"), ["C:/abc/efg.jpg","C:/abc/abc.png"], "formSubmit.jsp");
```

:::caution[Important]
If there are client side validations on file, [\_addResponseSubstitutionRule](https://resources.sahipro.com/docs/sahi-script/functions/http-responses/#_addresponsesubstitutionrule) and [\_removeResponseSubstitutionRule](https://resources.sahipro.com/docs/sahi-script/functions/http-responses/#_removeresponsesubstitutionrule) need to be used with \_setFile2 as following:

1.  add `_addResponseSubstitutionRule("fileUpload", ".*", true, "\\.files(?![a-zA-Z].*)", "._file");` to the script before navigating to page having file upload.
2.  add `_removeResponseSubstitutionRule("fileUpload");` after \_setFile2 and performing action for file upload submission.

```js
//when file element is not part of HTML Form and there are client side validations on File.
_addResponseSubstitutionRule("fileUpload", ".*", true, "\\.files(?![a-zA-Z].*)", "._file");
_setFile2(_file("id"), "C:/abc/efg.jpg", "formSubmit.jsp", "formSubmit.jsp", false, true);
_removeResponseSubstitutionRule("fileUpload");

_addResponseSubstitutionRule("fileUpload", ".*", true, "\\.files(?![a-zA-Z].*)", "._file");
_setFile2(_file("id"), ["C:/abc/efg.jpg","C:/abc/abc.png"], "formSubmit.jsp", false, true);
_removeResponseSubstitutionRule("fileUpload");

//when file element is part of HTML Form and there are client side validations on File.
_addResponseSubstitutionRule("fileUpload", ".*", true, "\\.files(?![a-zA-Z].*)", "._file");
_setFile2(_file("id"), "C:/abc/efg.jpg", "formSubmit.jsp", true, true);
//Perform action for file upload submission
_removeResponseSubstitutionRule("fileUpload");

_addResponseSubstitutionRule("fileUpload", ".*", true, "\\.files(?![a-zA-Z].*)", "._file");
_setFile2(_file("id"), ["C:/abc/efg.jpg", "C:/abc/abc.png"], "formSubmit.jsp", true, true);
//Perform action for file upload submission
_removeResponseSubstitutionRule("fileUpload");
```
:::

### _setFile

Since: Sahi Pro 3.5

Modes: Browser

```js
_setFile($element, $filePaths[, $actionURL])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$element` | HTML DOM element | HTML Form File Element whose value needs to be set |
| `$filePaths` | string\|array of strings | Path of the files to be uploaded. File path is resolved relative to current script file. |
| `$actionURL` | string (optional) | The form action URL to which the file is submitted. This is an optional parameter.<br>Use it in cases where the form's action URL is changed on setting the file.<br>By default, it uses the form's current action URL. |

Returns: `null`

```js
_setFile(_file("id"), "C:/abc/efg.jpg");
_setFile(_file("id"), "C:/abc/efg.jpg", "formSubmit.jsp");
```

:::caution[Important]
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.
:::

:::note
If there are javascript validations on the file field, use [`_setFile3`](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_setfile3) or [`_setFile2`](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_setfile2).
:::

### 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 changes when the form is submitted. In such a case, specify the third parameter `actionURL`. Refer [here](#identifying-action-url) to identify the Action URL.
3.  File upload with full path in Internet Explorer, find the detailed resolution [here](https://resources.sahipro.com/docs/troubleshooting/fileupload-with-fullpath-ie/).

### Identifying Action URL

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 Pro console. It will look something like this.

    ```js
    [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] using Set File Action or _setFile3 API.
    [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 `actionURL`.

:::note
Examples for \_setFile3 are available in sahi/userdata/scripts/sahitests/setFile3.sah.\
Examples for \_setFile and \_setFile2 are available in sahi/userdata/scripts/sahitests/fileUpload.sah.\
These 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.

```js
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
```

## File Download

<iframe width="560" height="315" src="https://www.youtube.com/embed/PP_9iZGze2s?si=bmE0TY8SsJuoOO06&start=215" title="Learn to download files using Sahi Pro" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen></iframe>

### File download overview

Sahi Pro detects file downloads, and automatically saves them to `sahi/userdata/temp/download` directory.\
Sahi Pro also adds the sessionId to the file name, so that multiple simultaneous tests do not overwrite each others files.\
For example, if you click on a "download" link which downloads a "setup.exe" file, this is how Sahi Pro 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 function: `_lastDownloadedFileName`
4.  Another function, `_saveDownloadedAs`, allows the file to be renamed and copied over to a convenient directory for you to work on.
5.  function `_clearLastDownloadedFileName` clears out the last downloaded file name so that further files can be downloaded and worked upon.

### _lastDownloadedFileName

Since: Sahi Pro 3.5

Modes: Browser

```js
_lastDownloadedFileName()
```

| Argument | Type | Description |
| --- | --- | --- |
| `None` |  |  |

Returns: `string` Name of the last downloaded file

Returns the last downloaded file name.

### _saveDownloadedAs

Since: Sahi Pro 3.5

Modes: Browser

```js
_saveDownloadedAs($path)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$path` | string | 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`

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

### _clearLastDownloadedFileName

Since: Sahi Pro 3.5

Modes: Browser

```js
_clearLastDownloadedFileName()
```

| Argument | Type | Description |
| --- | --- | --- |
| `None` |  |  |

Returns: `null`

Clears out the last downloaded file name so that further files can be downloaded and worked upon. After usig this, the function `_lastDownloadedFileName` will return empty untill another file is downloaded.

<span id="file-download-apis-example"></span>

### File download Functions example

```js
_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

:::note
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 the test run, 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

    ```js
    .*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

    ```properties
    download.download_if_contentdisposition_is_attachment=true
    ```

    in `sahi/userdata/config/userdata.properties`.

### Handling file downloads triggered in a new window

<iframe width="560" height="315" src="https://www.youtube.com/embed/KNXGYbHOeW8?si=cB5PD0HIyT9BSHXQ" title="Handle file downloads triggered in a new window" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen></iframe>

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 the `_sendHTMLResponseAfterFileDownload` function.

### _sendHTMLResponseAfterFileDownload

Since: Sahi Pro 4.3

Modes: Browser

```js
_sendHTMLResponseAfterFileDownload($enable[, $headers])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$enable` | boolean | true enables html response behaviour, false disables html response |
| `$headers` | object (optional) | Additional headers to be set in the HTML response sent after file download. This is available since Sahi Pro v9.1.1. |

Returns: `null`

Links to download files like PDF, Excel, Doc, etc. may open a new window. These windows may not have HTML content and thus cannot be automated. In such cases, use `_sendHTMLResponseAfterFileDownload` to send back an HTML response after file download.

Add `_sendHTMLResponseAfterFileDownload` with parameter `enable` as true before the step which triggers the download. To turn it off, add `_sendHTMLResponseAfterFileDownload`with parameter `enable` as false.

:::note
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.
:::

```js
_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);
```

:::note
Your application may expect specific headers in the response. HTML response sent by Sahi after file download may not contain those headers. So the application page would display an error. In such a case, we can specify `$headers` argument to set those headers in the HTML response as in the example below.

```js
_sendHTMLResponseAfterFileDownload(true, {"Access-Control-Allow-Origin":"https://test.example", "Access-Control-Allow-Credentials":"true"});
```
:::

### File download from a different domain

When a file is downloaded from a domain different than that of 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 Pro 4.5

Modes: Browser

```js
_addToSession($domain)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$domain` | string | Domain to be associated with the current script session |

Returns: `null`

Adds the domain to the current browser session during the test run.

:::note
When a file is downloaded from a domain different than that of the invoking page, the downloaded file is not associated with the current script session. In such cases, use `_addToSession` to add that domain to the current browser session.
:::

```js
// Add new domain url to Sahi's playback session
_addToSession("https://downloads.mydomain..example.com");
// NOTE _addToSession comes before click
_click(_link("Download"));
```

<span id="window-openclose-apis"></span>

## Window open/close Functions

### _closeWindow

Since: Sahi Pro 3.5, Desktop Engine 7.5.0, SAP Engine 9.0.0

Modes: Browser, Windows, Java, SAP

```js
_closeWindow([$title])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$title` | string (optional) | Title of the window to close. A regular expression can also be specified here. This argument is available only for SAP mode and Java mode. |

Returns: `null`

This function closes the current window. If the `title` argument is specified, this function closes the window having the specified title.

```js
// Close popup
_popup("popWin")._closeWindow();

// Close the current window in SAP mode
_closeWindow();

// Close a window having specified title in SAP mode or Java mode
_closeWindow("Create Inquiry");
_closeWindow("/Purchase Order No./");
_closeWindow("/Purchase Order No. [0-9]{5}/");
```

### _closeBrowser

Since: Sahi Pro 4.3.2

Modes: Browser

```js
_closeBrowser([$releaseCapacity])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$releaseCapacity` | boolean (optional) | Set to true if the browser was launched using _launchNewBrowser(). |

Returns: `null`

Closes the browsers in the current session in the middle of a run.

```js
_navigateTo("https://www.myapplication1.example.com");
_setValue(_textbox("user"), "test");
_setValue(_password("password"), "secret");
_click(_submit("Login"));
_closeBrowser();
_openBrowser();
_navigateTo("https://www.myapplication2.example.com");
_setValue(_textbox("q"), "2");
```

:::caution[Important]
Use with caution.

1.  This can be only used when singleSession is false in a suite.
2.  ALWAYS follow this with `_openBrowser()`or [\_launchNewBrowser()](https://resources.sahipro.com/docs/sahi-script/functions/multiple-browsers/#_launchnewbrowser). Otherwise the script will hang. When using `_launchNewBrowser()` use `_closeBrowser(true)`
3.  If multiple browsers is opened, then first use [\_selectBrowser()](https://resources.sahipro.com/docs/sahi-script/functions/multiple-browsers/#_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 Pro 4.3.2

Modes: Browser

```js
_openBrowser()
```

| Argument | Type | Description |
| --- | --- | --- |
| `None` |  |  |

Returns: `null`

Opens the browser in the current session in the middle of a run. This can be used to reopen browser after `_closeBrowser` function.

```js
_navigateTo("https://www.myapplication1.example.com");
_setValue(_textbox("user"), "test");
_setValue(_password("password"), "secret");
_click(_submit("Login"));
_closeBrowser();
_openBrowser();
_navigateTo("https://www.myapplication2.example.com");
_setValue(_textbox("q"), "2");
```

:::caution[Important]
Use 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](https://resources.sahipro.com/docs/sahi-script/functions/multiple-browsers/) for that
:::

### _openWindow

Since: Sahi Pro 5.0

Modes: Browser

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

| Argument | Type | Description |
| --- | --- | --- |
| `$url` | string (optional) | URL of the page to open. If no URL is specified, a new window with "about:blank" is opened. |
| `$name` | string (optional) | name of the window. |
| `$size` | array of integers (optional) | height and width of the window. |

Returns: `null`

Opens a new browser window.

```js
_openWindow("https://sahitest.com/demo/training/login.htm","defaultSahiPopup",[1280,600]);
```

## Calling Generic Code

### _call

Since: Sahi Pro 3.5, Mobile Engine 9.2.0

Modes: Browser, Android

```js
_call($expression)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$expression` | expression | Any expression which needs to be evaluated on the browser<br>Note that the expression is not quoted and is NOT a string. |

Returns: `string` The completion value of evaluating the given code. If the completion value is empty, undefined is returned.

\_call is a generic function to bypass Sahi's action functions and directly call javascript on the DOM.

```js
// 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 Pro 3.5, Mobile Engine 9.0.0

Modes: Browser, Android

```js
_eval($evalString)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$evalString` | string | Any string which needs to be javascript 'eval'ed on the browser |

Returns: `string` The completion value of evaluating the given code. If the completion value is empty, undefined is returned.

\_eval, like \_call, is a generic function to bypass Sahi's action functions and directly call javascript on the DOM.\
However, \_eval takes a string instead of an expression.

```js
// 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
```

:::caution[Important]
\_call is recommended over \_eval since \_call is easier to use.
:::

## Authentication

### _setClientCertificate

Since: Sahi Pro 9.2.0

Modes: Browser

```js
_setClientCertificate($path, $password, $keyStoreType)
```

| Argument | Type | Description |
| --- | --- | --- |
| `$path` | string | Client certificate file path. If path is relative, it is resolved relative to userdata directory. |
| `$password` | string | Client certificate password in encrypted format |
| `$keyStoreType` | string | Keystore type can be JCEKS, JKS, DKS, PKCS11 or PKCS12 |

Returns: `null`

Some applications seek a client certificate for authentication. This function sets the certificate to be used for authentication in the current script session. This function must be called before navigating to the application. Refer [Client Certificate Authentication](https://resources.sahipro.com/docs/sahi-script/client-certificate-authentication/) page for details.

```js
_setClientCertificate("c:/myownpath/testuser1.jks","Mg0BChVBGh1XOB0K", "JKS");

// Certificate file path can be specified relative to Sahi userdata directory.
_setClientCertificate("certgen/certs/testuser2.p12","MgkKEQBU", "PKCS12");
_setClientCertificate("certgen/certs/testuser3.pfx","MgkKEQBU", "PKCS12");
```

The domain of the application that requires client certificate authentication can be different than the domain of the invoking page. In such a case, the specified client certificate will not get used for your application. To solve this problem, add the application domain to the current script session using [\_addToSession](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_addtosession) function as shown in the example below.

```js
// Add the application domain that needs client certificate authentication to the current script session.
_addToSession("https://protectedapplication.test.com");

_setClientCertificate("certgen/certs/testuser1.p12","Mg0BChVBGh1XOB0K", "PKCS12");
```

:::note
-   For encrypting the password use [\_encrypt](https://resources.sahipro.com/docs/sahi-script/functions/utilities/#_encrypt) or use [password encoder](https://resources.sahipro.com/docs/using-sahi/sahi-script-editor/#password-encoder) from editor.
-   **Salt** is used to encrypt the password. You can change the **salt** by changing the property `script.salt_for_password_encryption` in `userdata/config/userdata.properties`file.
-   If `script.salt_for_password_encryption` property is present in `userdata/config/userdata_hidden.properties` as well, then this property will be considered only from `userdata_hidden.properties`file.
:::

### _setAuthentication

Since: Sahi Pro 11.2.0

Modes: Browser

```js
_setAuthentication($username, $password, $scheme[, $realm])
```

| Argument | Type | Description |
| --- | --- | --- |
| `$username` | string | Username for authentication |
| `$password` | string | Password for authentication |
| `$scheme` | string | HTTP Authentication schemes like Basic, Digest, NTLM, etc. |
| `$realm` | string (optional) | Authentication realm as requested by the authentication server |

Returns: `null`

Some applications seek HTTP authentication. This function can be used to add credentials for HTTP authentication schemes like Basic, Digest, NTLM, etc. Refer [401 Authentication](https://resources.sahipro.com/docs/sahi-script/401-authentication/) page for details to handle HTTP authentication.

This function must be added before navigating to the application. After this function gets executed, the credentials will be used for HTTP authentication in the current script session.

```js
// Add credentials to authenticate user 'user1' user for authentication realm 'Secure Gateway'.
_setAuthentication("user1", "JtkMEBE=", "", "Secure Gateway");

// Add credentials to authenticate user 'user2' user for authentication scheme 'basic'.
_setAuthentication("user2", "JtkMEBE=", "basic");

// To specify credentials for any authentication
_setAuthentication("user", "PtkMEGE=", "", "/.*/");
```

The domain of the application that requires authentication can be different than the domain of the invoking page. In such a case, the specified authentication credentials will not get used for your application. To solve this problem, add the application domain to the current script session using [\_addToSession](https://resources.sahipro.com/docs/sahi-script/functions/actions/#_addtosession) function as shown in the example below.

```js
// Add the application domain that needs authentication to the current script session.
_addToSession("https://protectedapplication.test.com");

_setAuthentication("guest", "JtkMEBE=", "basic");
```

:::note
-   For encrypting the password use [\_encrypt](https://resources.sahipro.com/docs/sahi-script/functions/utilities/#_encrypt) or use [password encoder](https://resources.sahipro.com/docs/using-sahi/sahi-script-editor/#password-encoder) from editor.
-   **Salt** is used to encrypt the password. You can change the **salt** by changing the property `script.salt_for_password_encryption` in `userdata/config/userdata.properties`file.
-   If `script.salt_for_password_encryption` property is present in `userdata/config/userdata_hidden.properties` as well, then this property will be considered only from `userdata_hidden.properties`file.
:::
