Fetch APIs
abstract
While working on scripts, we often need to fetch content from the application screen.
Examples may be:
Examples may be:
- Fetching and storing a generated userId for later use in script
- Getting the value of form field for verification
- Getting the text from a UI element for assertion
- Getting some particular attribute of a UI element, like href of a link
info
This API only works on elements which take user text input.
Parameters
$element | HTML DOM element | Form element whose value we need |
Return Value
string | Value of the element |
Modes Supported :
Raw Script
// Using in an assertion
_assertEqual("Tyto", _getValue(_textbox("company")));
// Fetching and storing value
var $userId = _getValue(_textbox("userId"));
Sahi Pro Classic API :_getValue
The returned string is normalized for different browsers. Multiple continuous spaces are replaced with single space.
Multiple continuous newlines are replaced with single newline. Newlines are always returned as \n even on
Mac and Linux, so that scripts can work across browsers and OSes.
This API uses the textContent or innerText attributes of elements.
Multiple continuous newlines are replaced with single newline. Newlines are always returned as \n even on
Mac and Linux, so that scripts can work across browsers and OSes.
This API uses the textContent or innerText attributes of elements.
Parameters
$el | HTML DOM element | Element whose text we need |
Return Value
string | Text content of the element |
Modes Supported :
Raw Script
// Using in an assertion
_assertEqual("Tyto", _getText(_div("companyDiv")));
// Fetching and storing value
var $userId = _getText(_div("userIdDiv"));
Sahi Pro Classic API :_getText
Specifies the filter data on input element which filters the list. This api should be used with _getOptions.
Eg.
_getOptions(Datalist Filter(_datalist("country_list"), "ind"));
returns array with all options matching with "ind" in the list.
Parameters
$el | HTML DOM element | Input or datalist element |
$filter | string optional | Data to filter (case-insensitive). |
Return Value
HTML DOM element |
Modes Supported :
Raw Script
Sahi Pro Classic API :_datalistFilter
If we want the values of all the options of the selectbox:
Parameters
$el | HTML DOM element | Select/ Input or associated datalist to the input element |
$type | string optional | Type can be specified as "value" or "text".
If the type is specified as "text" then text contents of all the options are returned. If the type is specified as "value" then values of all the options are returned. If the type is not specified then text contents of all the options are returned. |
Return Value
array of strings | Array containing the values or texts of all options of the select or datalist element |
Modes Supported :
Raw Script
var $list = _getOptions(_select("select_id"), "value");
_assertEqual("Value of First Option", $list[0]);
_assertEqual("Value of Second Option", $list[1]);
_assertEqual(2, $list.length);
Sahi Pro Classic API :_getOptions
Returns the text of the selected option in a select dropdown box.
Parameters
$el | HTML DOM element | Select dropdown element whose selected text we need |
Return Value
string | Text content of the selected option of a select dropdown |
Modes Supported :
Raw Script
// Using in an assertion
_assertEqual("18", _getSelectedText(_select("legalAge")));
// Fetching and storing value
var $legalAge = _getSelectedText(_select("legalAge"));
Sahi Pro Classic API :_getSelectedText
Returns the specified attribute's value for the element.
Parameters
$el | HTML DOM element | Element whose attribute we need |
$attributeName | string | The attribute to be fetched |
Return Value
string | The attribute value |
Modes Supported :
Raw Script
// Using in an assertion
_assertEqual("http://sahi.co.in/", _getAttribute(_link("Home"), "href"));
// Fetching and storing value
var $href = _getAttribute(_link("Home"), "href");
Sahi Pro Classic API :_getAttribute
It checks for existence of the element in the application. However, note that elements may exist but not be visible on the user interface.
infoFor testing, _isVisible is a better check than Exists.
infoFor testing,
Is Visible
Action is a better check than Exists
Action.Parameters
$el | HTML DOM element | Element to check |
Return Value
boolean | true if element exists on the page, else false |
Modes Supported :
Raw Script
// Using in an assertion
_assertTrue(_exists(_link("Home")));
// same as
_assertExists(_link("Home")));
// Fetching and storing value
var $exists = _exists(_link("Home"));
Sahi Pro Classic API :_exists
Compares two Javascript data type or arrays.
Parameters
$expected | any | Expected value.
This value can be any normal javascript data type or an array Regular expressions can also be used. (eg. "/del/") |
$actual | any | Actual value.
This value can be any normal javascript data type or an array. It is mostly some attribute of a HTML DOM element. |
Return Value
boolean | true if the expected and actual values match, else false |
Modes Supported :
Raw Script
// Compare string with regular expression.
var $compare1 = _areEqual("/^a.*c$/", "abc"); // $compare1 is true.
// Compare text of an element with regular expression.
var $compare2 = _areEqual("/created/", _getText(_div("result")));
// Compare arrays.
$exp = [/[a-z]+$/, "b"];
$act = ["ab", "b"];
var $compareArr = _areEqual($exp, $act); // $compareArr is true.
Sahi Pro Classic API :_areEqual
info
In 6.0.0, $checkZIndex and $doScroll have been newly added. Scripts written before 6.0.0 do NOT need changes.
Parameters
$el | HTML DOM element | Element to check |
$checkZIndex | boolean optional | If true, checks whether the element is on top or not(Checks whether some other element with a higher Z index is not hiding it). If false, omits this check.
Default is false. |
$doScroll | boolean optional | If true, checks whether element is the top element by scrolling to the element. If false, checks only for the current viewport.
Default is false. Used only when checkZIndex is true. |
Return Value
boolean | true if element is visible, else false |
Modes Supported :
Raw Script
// Using in an assertion
_assertTrue(_isVisible(_link("Home"))); // doesn't check z-index
_assertTrue(_isVisible(_link("Home"), true)); //checks z-index
_assertTrue(_isVisible(_link("Home"), true, true)); //checks z-index after scrolling
// Fetching and storing value
var $visible = _isVisible(_link("Home"));
Sahi Pro Classic API :_isVisible
Returns true if the element is checked. This is applicable for radio buttons and checkboxes.
Parameters
$el | HTML DOM element | Element to check |
Return Value
boolean | true if element is checked, else false |
Modes Supported :
Raw Script
// Using in an assertion
_assertTrue(_isChecked(_radio("Male")));
Sahi Pro Classic API :_isChecked
Some elements in your application could be disabled. This API returns true if the specified element is enabled.
Some elements in your application could be disabled. This action returns true if the specified element is enabled.
Parameters
$element | element | element to be check |
Return Value
boolean | true if element is enabled, else false |
Modes Supported :
Raw Script
// Using in an assertion
_assertTrue(_isEnabled(_button("Download")));
Sahi Pro Classic API :_isEnabled
Returns true if the element contains the specified text.
Parameters
$element | el | Element where we need to check if text is present |
$text | string | Text to check for. Can also be a regular expression |
Return Value
boolean | true if element contains the text, else false |
Modes Supported :
Raw Script
<div id="d1" style="background-color:yellow"><i>Formatted</i> Text</div>
Sahi Pro Classic API :_containsText
Returns true if the element contains the specified HTML content.
Parameters
$element | el | Element where we need to check if text is present |
$html | string | HTML to check for. Can also be a regular expression |
Return Value
boolean | true if element contains the HTML, else false |
Modes Supported :
Raw Script
<div id="d1" style="background-color:yellow"><i>Formatted</i> Text</div>
Sahi Pro Classic API :_containsHTML
Parameters
$parent | HTML DOM element | Parent element |
$child | HTML DOM element | Child element |
Return Value
boolean | true if the specified child element is a child of the specified parent element, else false |
Modes Supported :
Raw Script
<div id="d1">
<span>inside</span>
</div>
Sahi Pro Classic API :_contains
Parameters
None |
Return Value
string | Title of the top most page (the title visible on the browser) |
Modes Supported :
Raw Script
var $title = _title(); // returns "Sahi Pro - Fetch APIs" for this page.
Sahi Pro Classic API :_title
Parameters
$tableEl | HTML DOM element | Table element |
$columns | array of objects optional | Array of column identifiers. The identifiers can be index, text or regular expression of text |
$rows | string|integer|array of integers optional | Can be a regular expression, an array of indexes or the starting index |
$count | integer optional | If rows is the starting index, count is the ending index, If rows is a regular expression, count is the total count. If rows is an array of indexes, count is ignored. |
Return Value
two dimensional array of strings | The data from the table |
Modes Supported :
Raw Script
// All table data
var $data = _getTableContents(_table("tableId"));
// All rows, but only specific columns from the table
var $data = _getTableContents(_table("tableId"), [1,3,7] );
// Returns all rows with columns 2, 4 and 8 since index is 0 based.
// All rows, but only specific columns from the table
var $data = _getTableContents(_table("tableId"), [1,"Price", "/Stock/"] );
// Returns all rows with column 2 (index is 0 based), column with header "Price" and column header matching regular expression /Stock/
// Rows containing specified keyword, but only specific columns from the table
var $data = _getTableContents(_table("tableId"), ["Price", "/Stock/"], "/pen/" );
// Returns all rows containing words matching regular expression /pen/, with columns having column header Price and column header matching
// regular expression /Stock/. Note that /pen/ is matched with all the columns of the row.
// First n rows containing specified keyword, but only specific columns from the table
var $data = _getTableContents(_table("tableId"), ["Price", "/Stock/"], "/pen/", 8);
// Returns first 8 rows contain words matching regular expression /pen/ having column header Price and column header matching
// regular expression /Stock/
// Rows having indexes specified in array, with specific columns from the table
var $data = _getTableContents(_table("tableId"), ["Price", "/Stock/"], [3,4,7]);
// Returns rows 4, 5 and 8 (index is 0 based) having all columns with header "Price" and column header matching regular expression /Stock/
// Rows from m to n, but only specific columns from the table
var $data = _getTableContents(_table("tableId"), ["Price", "/Stock/"], 3, 7 );
// Returns rows from 3 to 7 having all columns with header "Price" and column header matching regular expression /Stock/
Sahi Pro Classic API :_getTableContents
info
Styles in HTML elements are calculated by the browser based on various CSS rules.
Style returns the computed style that is finally applicable to the element.
Accessing style directly as an attribute will not give computed style.
Always use Style instead.
Style returns the computed style that is finally applicable to the element.
Accessing style directly as an attribute will not give computed style.
Always use Style instead.
Parameters
$el | HTML DOM element | element whose style attribute we need |
$styleAttribute | string | style attribute to be fetched |
Return Value
string | The style attribute value |
Modes Supported :
Raw Script
// Using in assertion
_assertEqual("24px", _style(_heading1(0), "font-size"));
// Fetching and storing value
var $fontSize = _style(_heading1(0), "font-size");
Sahi Pro Classic API :_style
This may be used to verify layouts by comparing positions of specific elements.
Parameters
$el | HTML DOM element | element whose position we need |
$relative | boolean optional | If true, returns position relative to current viewport.
Default is false. |
Return Value
array of integers | An array [x,y] of the elements position in pixels relative to its window/frame/iframe |
Modes Supported :
Raw Script
// Using in assertion
_assertEqual([10,20], _position(_image("logo")));
// Fetching and storing value
var $position = _position(_image("logo"));
_log($position[0]); //logs x coordinate (eg. 10)
_log($position[1]); //logs y coordinate (eg. 20)
Sahi Pro Classic API :_position
This may be used inside native events to find the absolute positions of elements.
Parameters
$el | HTML DOM element | element whose position we need |
Return Value
array of integers | An array [x,y] of the elements absolute position in pixels |
Modes Supported :
Raw Script
// Using in assertion
var $xy = _positionNative(_link("Link Test"));
_assertEqual(222, $xy[1]);
// Fetching and storing value
var $xy = _positionNative(_link("Link Test"));
_log("x coordinate "+ $xy[0] ); //logs x coordinate of the element
_log("y coordinate "+ $xy[1] ); //logs y coordinate of the element
Sahi Pro Classic API :_positionNative
Parameters
$el | HTML DOM element optional | Element in which to look for selection. This is optional only for Browser Automation, as Sahi will automatically look in all frames and elements. |
Return Value
string | Text selected by the user (using mouse drag, like we select before copy paste) |
Modes Supported :
Raw Script
// Using in an assertion
_assertEqual("Search", _getSelectionText());
// Fetching and storing value
var $currentSelectedText = _getSelectionText();
Sahi Pro Classic API :_getSelectionText
Returns the text copied to the system clipboard by a web application.
infoJavascript's Clipboard API works only if the browser window is in focus. Additionally, browsers may impose further restrictions on accessing the clipboard. Therefore, it is imperative to use APIs _focusWindow and _clickNative, along with the
Get Copied Text
API, as shown in the example below.infoJavascript's Clipboard API works only if the browser window is in focus. Additionally, browsers may impose further restrictions on accessing the clipboard. Therefore, it is imperative to use Actions Focus Window and Click Native, along with the
Get Copied Text
Action.Parameters
None |
Return Value
string | Copied text |
Modes Supported :
Raw Script
_lockWindow();
_focusWindow();
_clickNative(_button("Copy Text to Clipboard"));
_unlockWindow();
var $copiedText = _getCopiedText();
_assertEqual("Copied text", $copiedText);
Sahi Pro Classic API :_getCopiedText
Browser Detection APIs
info
Browser detection APIs are used to identify browsers at runtime, so that specific paths in code can be chosen.
info
Useful for testing a responsive website. Refer to _getScreenSize
Parameters
None |
Return Value
string | The userAgent string of the current browser |
Modes Supported :
Raw Script
Sahi Pro Classic API :_userAgent
Parameters
None |
Return Value
array of integers | Screen size as an array [x,y]. The first value is the inner width of the browser window and the second value is the inner height |
Modes Supported :
Raw Script
// Using in an assertion
var $screensize=_getScreenSize();
_assertTrue(($screensize[0]>=783)&&($screensize[0]<=800));
_assertTrue(($screensize[1]>=280)&&($screensize[1]<=400));
Sahi Pro Classic API :_getScreenSize
Parameters
None |
Return Value
boolean | true if the current browser is Internet Explorer, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isIE
Parameters
None |
Return Value
boolean | true if the current browser is Internet Explorer 9, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isIE9
Parameters
None |
Return Value
boolean | true if the current browser is Internet Explorer 10, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isIE10
Parameters
None |
Return Value
boolean | true if the current browser is Edge, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isEdge
Parameters
None |
Return Value
boolean | true if the current browser is new Microsoft Edge, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isEdgeNew
Parameters
None |
Return Value
boolean | true if the current browser is Firefox, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isFF
Parameters
None |
Return Value
boolean | true if the current browser is Firefox 3, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isFF3
Parameters
None |
Return Value
boolean | true if the current browser is Firefox 4, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isFF4
Parameters
None |
Return Value
boolean | true if the current browser is Chrome, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isChrome
Parameters
None |
Return Value
boolean | true if the current browser is Safari, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isSafari
Parameters
None |
Return Value
boolean | true if the current browser is Opera, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isOpera
Parameters
None |
Return Value
boolean | true if the current browser is PhantomJS, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isPhantomJS
Parameters
None |
Return Value
boolean | true if the current browser is Brave, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isBrave
Parameters
None |
Return Value
boolean | true if the current browser is HTMLUnit, else false |
Modes Supported :
Raw Script
Sahi Pro Classic API :_isHTMLUnit
Rich Text Editors (Content Editable elements)
infoRefer to RTE APIs.
Generic attribute fetching mechanism
Most common attributes needed during automation are exposed via Sahi's fetch APIs.However there are lots of DOM attributes which are not exposed.
For example the href attribute of a link is not exposed by any in-built Sahi API.
To work with such attributes, the APIs _fetch, _set and _condition are used.
info
_fetch is a newer API and can be used in place of both _set and _condition.
info
Fetch API was introduced later than _set and may be a cleaner way.
For secondary (popup) windows, Fetch can be used only with _selectWindow and not with _popup prefix.
For secondary (popup) windows, Fetch can be used only with _selectWindow and not with _popup prefix.
Parameters
$expression | string|DOM expression | Expression which we wish to evaluate and fetch. |
Return Value
string | Value of the expression |
Modes Supported :
Raw Script
var $rowCount = _fetch(_table("tableId").rows.length);
// You can also use an expression as a string
var $userAgent = _fetch("navigator.userAgent");
// And fetch results of custom utility functions of your web app
var $value = _fetch("jQuery('#id').val()");
// While working with popup windows use _selectWindow first
_selectWindow("popupWin");
// Fetch table row count from popupWin window
var $rowCount = _fetch(_table("tableId").rows.length);
Sahi Pro Classic API :_fetch
Sets the value of expression into variable
Set communicates with the browser to evaluate the expression and fetches the result.
Set communicates with the browser to evaluate the expression and fetches the result.
warning
_fetch may be a better way than Set to fetch values from browser.
Parameters
$variable | variable | Variable into which we wish to get the specific value. |
$expression | DOM Expression | Expression which we wish to evaluate and set. |
Return Value
Modes Supported :
Raw Script
// Fetching href attribute
var $href = null; // initialize variable
_set($href, _link("Home").href); // set it
// Getting row count of table
var $rowCount = 0; // initialize variable
_set($rowCount, _table("tableId").rows.length); // set it
// Getting column count of table (first row)
var $colCount = 0; // initialize variable
_set($colCount, _table("tableId").rows[0].cells.length); // set it
Sahi Pro Classic API :_set
Parameters
$expression | DOM expression | Expression which we wish to evaluate. |
Return Value
boolean | true or false based on the expression |
Modes Supported :
Raw Script
if (_condition(_link(0).href == "http://sahi.co.in/")){
_click(_link(0));
}
// Note that this is the same as
var $href = _fetch(_link(0).href);
if ($href == "http://sahi.co.in/"){
_click(_link(0));
}
// or
var $href = null;
_set($href, _link(0).href);
if ($href == "http://sahi.co.in/"){
_click(_link(0));
}
Sahi Pro Classic API :_condition
Multiple Elements
info
These APIs are used to fetch content from multiple elements.
Parameters
$elementType | string | type of elements to collect. Eg. "_link" , "_button" , "/text/" etc. |
$identifier | string | Sahi Identifier. Can also be just an index. |
$relations | relations optional | Relations like _in, _near etc. |
Return Value
array of element stubs | Array of all elements of the specified type matching the identifier within relations |
Modes Supported :
Raw Script
// Collect all textboxes matching any identifier, in table "listing".
// Note the use of match all regular expression "/.*/"
var $textboxes = _collect("_textbox", "/.*/", _in(_table("listing"));
// Iterate and set values on all textboxes
for (var $i=0; $i<$textboxes.length; $i++) {
_setValue($textboxes[$i], "value");
}
Sahi Pro Classic API :_collect
Parameters
$elementType | string | type of elements to collect. Eg. "_link" , "_button" , "/text/" etc. |
$identifier | string|object | Sahi Identifier/Attributes JSON. Can also be just an index. |
$relations | relations optional | Relations like _in, _near etc. |
Return Value
integer | Count of all elements of the specified type matching the identifier within relations |
Modes Supported :
Raw Script
// Count all textboxes matching any identifier, in table "listing".
// Note the use of match all regular expression "/.*/"
var $textboxCount = _count("_textbox", "/.*/", _in(_table("listing")); // may return 5;
// or more explicitly
var $textboxCount = _count("_textbox", {name:"q"});
Sahi Pro Classic API :_count
Fetching a simple attribute from multiple elements
Parameters
$elementType | string | type of elements to collect.
Eg. "_link" , "_button" , "/text/" etc. |
$identifier | string | Sahi Identifier. Can also be just an index. |
$attribute | string|function | attribute or function. |
$relations | relations optional | Relations like _in, _near etc. |
Return Value
li_s | Array of element attributes of all elements of the specified type matching the identifier within relations |
Modes Supported :
Raw Script
// Collect the id attribute of all textboxes in table "listing".
// Note the use of match all regular expression "/.*/"
var $textboxIds = _collectAttributes("_textbox", "/.*/", "id", _in(_table("listing")));
// Collect text of divs whose className is menu-item
var $menuTexts = _collectAttributes("_div", "menu-item", "sahiText");
// or more explicitly
var $menuTexts = _collectAttributes("_div", {className:"menu-item"}, "sahiText");
Sahi Pro Classic API :_collectAttributes
Parameters
$elementType | string | Type of elements to collect. Can be regular expression.
Eg. "_link" , "_button" , "/text/" etc. |
$relations | relations optional | Relations like _in, _near etc. |
Return Value
array of objects | Array of Accessor Info object of all elements of the specified type within relations |
Modes Supported :
Raw Script
var $accs1 = _collectElementsInfo("/text/"); // Collect all _textbox and _textarea accessor info.
// Collect all _radio accessor infos in div "modes".
var $accs = _collectElementsInfo("_radio", _in(_div("modes")));
/*
$accs = [
{"api":"_radio", "identifiers":{"id":"sahiradio", "index":0, "name":"mode", "value":"on"}, "tag":"INPUT"},
{"api":"_radio", "identifiers":{"id":"javaradio", "index":1, "name":"mode[1]", "value":"on[1]"}, "tag":"INPUT"},
{"api":"_radio", "identifiers":{"id":"rubyradio", "index":2, "name":"mode[2]", "value":"on[2]"}, "tag":"INPUT"}
]
*/
for (var $i=0; $i<$accs.length; $i++) {
var $obj = $accs[$i];
var $identifiers = $obj["identifiers"];
var $el = $obj["api"] + "(\"" + $identifiers["id"] + "\")";
_log($el);
}
Sahi Pro Classic API :_collectElementsInfo