Top Rounds
[Hide Navigation]

All APIs ·

Browser Accessor APIs

Overview

Browser Accessor APIs help access elements on the browser.
They need to be executed on the browser and not in the proxy.
They should be used as parameters to Browser Action APIs.

All accessor APIs take an identifier and an optional domRelation.

  • Identifiers can either be a numerical index or a property as specified in each case.
  • Identifiers which are not numerical, can either be a string or a javascript regular expression.
  • Identifiers which are strings can also have an index along with them in square brackets as part of the string.

Simple case where links are uniquely identifiable:

For example,

<a href="http://sahi.co.in" id="sahi_link">Link to Sahi website</a>

can be represented in the following ways:

_link(12) Using index in the page; assuming it is the 13th link on the page.
_link("sahi_link") Using id as string
_link(/.*_link/) Using id as regular expression
_link("Link to Sahi website") Using visible text as string
_link(/Link to .* website/) Using visible text as regular expression
_link("/Link to .* website/") Using visible text as regular expression
_link({id:"sahi_link"}) Using an associative array with id
_link({sahiText:"/Link to .*/"}) Using an associative array with visible text as regular expression
_link({className:"low",sahiText:"/Link.*/"}) Using an associative array with multiple attributes like className and sahiText

Case where multiple elements with similar property are present

For example,

<table>
    <tr>
        <td>User One</td> 
        <td id="del1"><a href="/deleteUser?id=1">delete</a></td> 
    </tr>
    <tr> 
        <td>User Two</td> 
        <td id="del2"><a href="/deleteUser?id=2">delete</a></td> 
    </tr>
</table>

There are two delete links in this table and there may be more.

_link("delete") points to the first delete link. This is the same as _link("delete[0]").
_link("delete[1]") points to the second delete link; Note that indexing starts at 0.
_link("/del/[1]") points to the second delete link; Note that indexing starts at 0.

Using indexes works fine as long as the page is static, but it is not recommended for dynamic applications,
as it makes scripts fail when changes are made to the web pages.

Use of DOM relations

When elements are not uniquely identifiable by themselves, we should try to identify them in relation to either some element near them or by the element in which they are contained.
_near is a DOM relation marker which specifies that the element should be searched near another element.
_in is a DOM relation marker which specifies that the element should be searched within another element.

For example, in the above case, the second delete link is near User Two.

_link(0, _near(_cell("User Two"))) points to the 0th link near cell with text “User Two”.
Note that the index is 0 here since it is the nearest link.
_link("delete", _near(_cell("User Two"))) points to the nearest link with text “delete” near cell with text “User Two”.
Note that we do not need to specify "delete[1]" since it is the delete.
link
nearest to User Two.
_link(/del/, _near(_cell("User Two"))) points to the nearest link with text which matches
regular expression /del/ near cell with text “User Two”.
_link("delete[2]", _near(_cell("User Two"))) points to the 3rd nearest link with text “delete” near cell with text “User Two”.
_link("/del/[2]", _near(_cell("User Two"))) points to the 3rd nearest link with text matching /del/ near cell with text “User Two”.
Note how the regular expression is appended with the index in square brackets
and quoted to make it a string

A similar DOM relation is _in

_link(0, _in(_cell("del2"))) points to the 0th link in cell with id “del2”
_link("delete", _in(_cell("del2"))) points to the link with text “delete” within cell with id “del2”

Use of Positional relations

_under is a Positional Relation which helps narrow down elements under another element.
Specifically it looks for elements which have the same left offset (within a threshold) as the anchoring element.
_under is available since 2010-06-10

One important frequent requirement in web applications is the assertion of elements in a column of a grid. For example

Name Delete Status
User One delete Active
User Two delete Inactive
<table>
    <tr>
        <td>Name</td> 
        <td>Delete</td> 
        <td>Status</td> 
    </tr>
    <tr>
        <td>User One</td> 
        <td id="del1"><a href="/deleteUser?id=1">delete</a></td> 
        <td>Active</td> 
    </tr>
    <tr> 
        <td>User Two</td> 
        <td id="del2"><a href="/deleteUser?id=2">delete</a></td> 
        <td>Inactive</td> 
    </tr>
</table>

In the above table:

_cell(0, _near(_cell("User One")), _under(_cell("Status"))) Finds first cell near User One and under Status
_cell("Inactive", _under(_cell("Status"))) Finds first Inactive cell under Status


More examples




Accessors of HTML Elements



API _link(identifier[, domRelation])
HTML

<a href="http://u/r/l" id="id">visible text</a> 
Identifier index, visible text, id.



API _image(identifier[, domRelation])
HTML

<img src="/path/to/images/add.gif" id="id" alt="alt" title="title">
Identifier index, title or alt, id, file name from src
Notes _image(“add.gif”) for an image with src “/path/to/images/add.gif”



API _label(identifier[, domRelation])
HTML

<label id="id">text</label>
Identifier index, id, text



API _listItem(identifier[, domRelation])
HTML

<li id="id">text</li>
Identifier index, id, text



API _dList(identifier[, domRelation])
HTML

<dl id="list">  <dt>Coffee</dt>    </dl>
Identifier index, id, text



API _dTerm(identifier[, domRelation])
HTML

<dt>Coffee</dt> 
Identifier index, id, text



API _dDesc(identifier[, domRelation])
HTML

<dt>Coffee</dt>
    <dd>Black hot drink</dd>
Identifier index, id, text



API _div(identifier[, domRelation])
HTML

<div id="id">text</div>
Identifier index, id, text



API _span(identifier[, domRelation])
HTML

<span id="id">text</span>
Identifier index, id, text



API _spandiv(identifier[, domRelation])
HTML

<span id="id">text</span> or <div id="id">text</div>
Identifier index, id, text
Notes Deprecated



API _heading1(identifier[, domRelation])
HTML

<h1 id="id">text</h1>
Identifier text, id



API _heading2(identifier[, domRelation])
HTML

<h2 id="id">text</h2>
Identifier text, id



API _heading3(identifier[, domRelation])
HTML

<h3 id="id">text</h3>
Identifier text, id



API _heading4(identifier[, domRelation])
HTML

<h4 id="id">text</h4>
Identifier text, id



API _heading5(identifier[, domRelation])
HTML

<h5 id="id">text</h5>
Identifier text, id



API _heading6(identifier[, domRelation])
HTML

<h6 id="id">text</h6>
Identifier text, id



API _title()
HTML

<title>text</title>
Notes Returns title of the page



API _area(identifier[, domRelation])
HTML

<area shape="rect" class="className" id="id" href="http://u/r/l" />
Identifier id, title|alt, href, shape, className, index
Notes -



API _blockquote(identifier[, domRelation])
HTML

<blockquote class="className" id="id">sahiText</blockquote>
Identifier sahiText, id, className, index
Notes -



API _bold(identifier[, domRelation])
HTML

<b class="className" id="id">sahiText</b>
Identifier sahiText, id, className, index
Notes -






API _code(identifier[, domRelation])
HTML

<code class="className" id="id">sahiText</code>

Identifier sahiText, id, className, index
Notes -



API _emphasis(identifier[, domRelation])
HTML

<em class="className" id="id">sahiText</em>
Identifier sahiText, id, className, index
Notes -



API _italic(identifier[, domRelation])
HTML

<i class="className" id="id">sahiText</i>
Identifier sahiText, id, className, index
Notes -






API _list(identifier[, domRelation])
HTML

<ul class="className" id="id">sahiText</ul>


<ol class="className" id="id">sahiText</ol>

Identifier id, className, index
Notes -






API _map(identifier[, domRelation])
HTML

<map class="className" id="id"></map>

Identifier name, id, title, className, index
Notes -






API _canvas(identifier[, domRelation])
HTML

<canvas class="classname" id="id"></canvas>

Identifier sahiText, id, className, index
Notes -

API _applet(identifier[, domRelation])
Identifier sahiText, id, className, index
Notes -
API _flex()
Identifier sahiText, id, className, index
Notes Same as _f(), used to identify the objects in flex application.






API _preformatted(identifier[, domRelation])
HTML

<pre class="className" id="id">sahiText</pre>

Identifier sahiText, id, className, index
Notes -






API _strong(identifier[, domRelation])
HTML

<strong class="className" id="id">sahiText</strong>

Identifier sahiText, id, className, index
Notes -







API _abbr(identifier[, domRelation])
HTML

<abbr class="className" id="id">sahiText</abbr>

Identifier sahiText, id, className, index
Notes -
Since 2011-07-19

Accessors of Table related elements



API _cell(identifier[, domRelation])
HTML

<td id="id">text</td>
Identifier index, id, text




API _cell(tableElement, rowText, colText)
HTML

<td id="id">text</td>
Notes
<table id="tableId">
<tr><td> header1 </td><td> header2 </td><td> header3 </td></tr>
<tr><td> value11 </td><td> value12 </td><td> value13 </td></tr>
<tr><td> value21 </td><td> value22 </td><td> value23 </td></tr>
</table>


Eg.
_cell(_table("tableId"), "header2", "value11") will point to cell with value “value12”
(Need to add support for regular expressions for rowText and colText)



API _row(identifier[, domRelation])
HTML

<tr><td>te</td><td>xt</td></tr>
Identifier id, className, text, index
Notes _row(“text”) can be used to identify rows with text. Useful to look for cells in a row. _cell(“text1”, _in(_row(“someClassName”)))
The older _row(tableElement, identifier) has been phased out since 2010-06-10. To get the same functionality, use _row(identifier, _in(tableElement)), consistent with the other APIs.



API _table(identifier[, domRelation])
HTML

<table id="id">text</table>
Identifier index, id



API _tableHeader(identifier[, domRelation])
HTML

<th id="id">text</th>
Identifier text, id

Accessors of Form elements



API _button(identifier[, domRelation])
HTML

<input type="button" name="name" id="id" value="value">
HTML
<button type="button" name="name" id="id">value</button>
Identifier index, value, name, id



API _checkbox(identifier[, domRelation])
HTML

<input type="checkbox" name="name" id="id" value="value">
Identifier index, name, id



API _paragraph(identifier[, domRelation])
HTML

<p name="name" id="id">This is a paragraph</p>
Identifier index, name, id



API _password(identifier[, domRelation])
HTML

<input type="password" name="name" id="id" value="value">
Identifier index, name, id



API _radio(identifier[, domRelation])
HTML

<input type="radio" name="name" id="id" value="value">
Identifier index, name, id



API _submit(identifier[, domRelation])
HTML

<input type="submit" name="name" id="id" value="value">
HTML
<button type="submit" name="name" id="id">value</button>
Identifier index, value, name, id



API _textbox(identifier[, domRelation])
HTML

<input type="textbox" name="name" id="id" value="value">
Identifier index, name, id



API _reset(identifier[, domRelation])
HTML

<input type="reset" name="name" id="id" value="value">
Identifier index, name, id



API _file(identifier[, domRelation])
HTML

<input type="file" name="name" id="id" value="value">
Identifier index, name, id



API _imageSubmitButton(identifier[, domRelation])
HTML

<input type="image" name="name" id="id" value="value" alt="alt" title="title" src="/images/file.gif">
Identifier index, tilte/alt, name, id
Notes (Add support to treat this like _image)



API _select(identifier[, domRelation])
HTML

<select name="name" id="id"></select>
Identifier index, name, id



API _option(identifier[, domRelation])
HTML

<option id="id" value="value">text</option>
Identifier text, value, id, index
Notes eg. _option("text") or _option("text", _in(_select("selectedId")))

_option(selectElement, identifier) has been phased out since 2010-06-10. Please use _option(identifier, _in(selectElement)) instead.



API _textarea(identifier[, domRelation])
HTML

<textarea name="name" id="id">text</textarea>
Identifier index, name, id



API _hidden(identifier[, domRelation])
HTML

<input type="hidden" name="name" id="id" value="value">
Identifier index, name, id
h3. Accessor using Selenium locators



API _bySeleniumLocator(seleniumLocator)*
Identifier any selenium identifier, eg. _bySeleniumLocator(xpath)

Accessors of HTML5 Form elements



API _timebox(identifier)
HTML

<input type="time" name="name" id="id" value="value"/>
Identifier index, name, id



API _datebox(identifier)
HTML

<input type="date" name="name" id="id" value="value"/>
Identifier index, name, id



API _datetimebox(identifier)
HTML

<input type="datetime" name="name" id="id" value="value"/>
Identifier index, name, id



API _datetimelocalbox(identifier)
HTML

<input type="datetime-local" name="name" id="id" value="value"/>
Identifier index, name, id



API _weekbox(identifier)
HTML

<input type="week" name="name" id="id" value="value"/>
Identifier index, name, id



API _monthbox(identifier)
HTML

<input type="month" name="name" id="id" value="value"/>
Identifier index, name, id



API _numberbox(identifier)
HTML

<input type="number" name="name" id="id" value="value"/>
Identifier index, name, id



API _rangebox(identifier)
HTML

<input type="range" name="name" id="id" value="value" min="min" max="max"/>
Identifier index, name, id



API _telephonebox(identifier)
HTML

<input type="tel" name="name" id="id" value="value"/>
Identifier index, name, id



API _emailbox(identifier)
HTML

<input type="email" name="name" id="id" value="value"/>
Identifier index, name, id



API _urlbox(identifier)
HTML

<input type="url" name="name" id="id" value="value"/>
Identifier index, name, id



API _searchbox(identifier)
HTML

<input type="search" name="name" id="id" value="value"/>
Identifier index, name, id

Accessors of parent DOM Nodes

All parent node accessors can take two parameters:
element: The element whose parent node needs to be found
occurrence: The nth parent. 1 is the immediate parent.

Eg.
In <div id="div2"><span><div id="div1"><a href="">aLink</a></div></span></div>
_parentNode(_link(“aLink”), “DIV”, 1) points to div1
_parentNode(_link(“aLink”), “DIV”, 2) points to div2



API _parentNode(element, tagname[, occurrence])
HTML

<div id="id"><a href="">aElement</a></div>
Notes eg. _parentNode(“DIV”, _link(“aElement”))



API _parentCell(element[, occurrence])
HTML

<td id="id"><a href="">aElement</a></td>
Notes eg. _parentCell(_link(“aElement”))



API _parentRow(element[, occurrence])
HTML

<tr><td>aCell</td></tr>
Notes eg. _parentRow(_cell(“aCell”))



API _parentTable(element[, occurrence])
HTML

<table class="api">
<tr><td>aCell</td></tr></table>
Notes eg. _parentTable(_cell(“aCell”))

Accessors of IFrames and Rich Text Editors based on IFrames in editable mode.



API _rte(identifier)
HTML

<iframe src="" name="name" id="id" ></iframe>
Identifier index, id, name



API _iframe(identifier)
HTML

<iframe src="" name="name" id="id" ></iframe>
Identifier index, id, name

Generic accessors



API _byId(id)
HTML

<anytag id="id" ></anytag>
Identifier id
Notes This can be used for any tag with an id. This API does not accept regular expressions or indexes.



API _byText(identifier, tagName)
HTML

<anytag>text</anytag>
Identifier text
Notes This can be used for any tag with text.



API _byClassName(identifier, tagName[, domRelation])
HTML

<anytag class="className">text</anytag>
Identifier className
API _byXPath(xpath[, domRelation])
Identifier xpath expression as string
Notes Eg.

_byXPath("//table[3]//tr[1]/td[2]")
_byXPath("//tr[1]/td[2]", _in(_table(2)))

This is a convenience method for people moving from Selenium or other tools to Sahi.

XPaths are natively enabled on Firefox. For browsers like Internet Explorer which do not have support for XPath use Javascript-XPath. Copy the contents of javascript-xpath-latest.js and save the contents to sahi/htdocs/spr/ext/javascript-xpath/javascript-xpath.js and there is a README.txt which has these instructions

This file is under its own MIT license and is not part of Sahi’s code base
API _accessor(string)
Notes This API just evaluates the string and returns a dom object. Eg. _accessor(“document.formName.elementName”).
This API is not too useful.

Browser popups: Alerts, Confirms and Prompts

_lastAlert, _lastConfirm and _lastPrompt are used in assertions.
Eg. _assertEqual(“Enter a valid username”, _lastAlert());

API _lastAlert()
Notes Returns the message displayed in the last javascript alert popup.
API _lastConfirm()
Notes Returns the message displayed in the last javascript confirm popup.
API _lastPrompt()
Notes Returns the message displayed in the last javascript prompt popup.
API _printCalled()
Notes Returns true if window.print() had been invoked.

Utility functions to access properties of elements

API _style(element, cssProperty)
cssProperty any property declared via CSS. Eg. height, background-color etc.
Notes Returns the value of the style property for that element. Eg. For <td style="background-color:red">cell text</td> _style(_cell(“cell text”), “background-color”) returns “red”
API __activeElement()
Notes Returns the element which is in focus.
API _cookie(cookieName)
Notes Returns the value of the cookie with cookieName.
API _position(element)
Notes Returns the an array with the element’s x, y coordinate in pixels. Eg. _position(_div(“id”)) may return [100, 180]
API _getText(element)
Notes Returns the innerText or textContent of an element. Eg. For <div id="divId">This is some <b>bold</b> <a href="">link</a></div> _getText(_div(“divId”)) will return “This is some bold link”.
API _getAttribute(element)
Notes Returns the attribute of a particular element.
API _extract(string, pattern, groupsOnly)
Notes Returns an array of matching elements. Pattern needs to be a valid regular expression.
API _getValue(element)
Notes Returns the Value of an element.
API _getCellText(cellElement)
Notes Deprecated. Same as _getText
API _getSelectedText(selectElement)
Notes Returns the text of the selected option in a <select> tag
API _rteHTML(element)
Notes Returns the html inside a rich text editor. Eg. _rteHTML(_rte(“rteId”)) will return the rich text editor’s contents.
API _rteText(element)
Notes Returns the text inside a rich text editor. Eg. _rteText(_rte(“rteId”)) will return the rich text editor’s text content (without the html formatting).
API _isVisible(element)
Notes Returns true if the element is visible on the user interface. Can be used to assert if a mouse over menu has appeared or not.
API _exists(element)
Notes Returns true if the element exists. Same as checking element != null.
API _containsText(element, text)
Notes Returns true if the element contains the given text Eg. For <div id="divId">some text</div> _containsText(_div(“divId”), “some”) returns true
API _containsHTML(element, html)
Notes Returns true if the element contains the given html Eg. For <div id="divId">some <b>text</b></div> _containsHTML(_div(“divId”), “text“) returns true
API _contains(parentElement, childElement)
Notes Returns true if childElement is a child of parentElement

Marker functions to show DOM relation

API _in(element)
Notes Refer to “DOM Relations”
API _near(element)
Notes Refer to “DOM Relations”

Marker functions to show Positional relation

API _xy(element, x, y)
Notes Specifies the coordinates on element where the event is fired.

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

Negative values can be given to specify offset from right and bottom.
Eg. _click(_xy(_button("id"), -5, -10)) clicks inside the button, 5px from the right and 10px from the bottom.
API _under(element)
Notes _under is a Positional Relation which helps narrow down elements which have the same left offset (within a threshold) as element. Refer to section on “Positional Relations” above for example. _under can be used as a last parameter to any Sahi Accessor API
Since2010-06-10
API _above(element)
Notes Refer to “DOM Relations”
API _aboveOrUnder(element)
Notes Refer to “DOM Relations”
API _leftOf(element)
Notes Refer to “DOM Relations”
API _rightOf(element)
Notes Refer to “DOM Relations”
API _leftOrRightOf(element)
Notes Refer to “DOM Relations”


Miscellaneous APIs

Functions available on browser and on proxy


API _random(limit)
Notes Returns a random number between 0 and limit. Details

API _scriptName()
Notes Returns the name of the current script

API _scriptStartTime()
Notes Returns the start time of the execution.

API _resolvePath()
Notes Returns the name of the current script

API _stackTrace()
Notes Returns the absolute path with reference to the present script.

API _stackTrace()
Notes Returns the absolute path with reference to the present script.

API _scriptStatus()
Notes Returns Success or Failure for current script

API _fail()
Notes Aborts the scripts and exits.

API _dynamicInclude()
Notes Includes a file at runtime based on conditions provided by user in script.

API _popup(identifier)
Identifier windowName, windowTitle
Notes Returns a handle to the window. The identifier can be a regular expression.
_popup() is used as a prefix to statements which need to be executed on another window.

Eg.
 _popup("popWin")._click(_link("Click me"));
_popup(/popWin.*/)._click(_link("Click me"));
_popup("Window Title")._click(_link("Click me"));
Related _poup and _set

API _domain(identifier)
Identifier Domain Name
Notes Returns a handle to the element in different domain.
_domain() is used as a prefix to statements which need to be executed on another domain but are in the same base window.

Eg.
_domain("www.tytosoftware.com")._click(_link("Link Test"));
_domain("www.bing.com")._setValue(_textbox("q"), "sahi forums");
_domain("www.bing.com")._click(_submit("go"));

API _selectDomain(identifier)
Identifier Domain Name
Notes Returns a handle to the element in different domain.
_selectDomain(identifier) is used to select the domain for statements which need to be executed on another domain but are in the same base window.

_selectDomain() will return to the base domain. Eg.
_selectDomain("www.tytosoftware.com")
_click(_link("Link Test"));
_setValue(_textbox("q"), "sahi forums");
_click(_submit("go"));
_selectDomain();

API _selectWindow(popupId)
popupId windowName, windowTitle; if left blank, it chooses the base window
Notes Sets the given window as context for the following Sahi statements.
The identifier can be a regular expression.
This API helps make scripting easier when most actions are performed on a popup window.

Eg.
_selectWindow("popWin"); // select popWin
// further statements will be performed on popWin
_click(_link("Click me")); // will click on popWin
_click(_button("Done")); // will click on popWin
_selectWindow(); // select base window
// further statements will be performed on base window
_click(_button("Finished")); // clicks on base window;

API _sessionInfo()
Notes Returns information of the current session. The object has attributes:
  • isRecording: returns true if recording
  • isPlaying: returns true if playingback
  • isPaused: returns true if playback is paused
  • sessionId: returns Sahi’s sessionId
  • threadNumber: returns the threadNumber of browser instance running
  • scriptPath: returns script path of current script. Same as _scriptPath()

API _suiteInfo()
Notes Returns information of the current session. The object has attributes:
  • suiteName: name of suite
  • suitePath: Path of suite
  • base: Base url for suite
  • browser: Browser executable path
  • browserOption: browserOption passed to Suite
  • browserProcessName: browserProcessName passed to Suite
  • sessionId: SessionId of suite

API _userDataDir()
Notes Returns absolute path to userdata directory, given a relative path.

API _userDataPath()
Notes Returns the path to userdata.

API _lastDownloadedFileName()
Notes Normally Sahi sends back a 204 response so that the browser stays on the same page. Using _sendHTMLResponseAfterFileDownload (true) forces Sahi to return back an HTML response. This is needed when your application triggers the download from a new window (eg. with a PDF or a word doc). Add this before the step which triggers the download.

API _sendHTMLResponseAfterFileDownload (boolean)
Notes This is used to demarcate testcase boundaries when running csv files as suites. Details

API _testcase()
Notes Returns the name of the last downloaded file name. Details

API _setStrictVisibilityCheck(boolean)
Notes
// make Sahi ignore elements which are not visible.
_setStrictVisibilityCheck(true); 
// make sahi revert to original behavior of considering all elements in the DOM.
_setStrictVisibilityCheck(false);

This API is useful in cases where widgets are dynamically created at multiple locations but only one of them is visible at any given time.

During recording Sahi can be forced into either mode by choosing “Strict Visibility On” or “Strict Visibility Off” from the “Other Actions:” dropdown. Make sure you “Append to Script” to add it to the recorded script

API _setHttpHeader(key, value)
Notes This will modify the key value pair in the HTTP header being sent to the server, so that all the headers sent further will have this changed value.
Eg.
_setHttpHeader("User-Agent", $userAgent);
This will set the User-Agent to the value in the variable passed and all further headers will contain this value of User-Agent.

API _addHttpHeader(key, value)
Notes This will add the key value pair in the HTTP header being sent to the server, so that all the headers sent further will also have this new value.

Eg.
 _addHttpHeader("New-Agent", $userAgent);

This will add a new Value of New-Agent and also pass this with the HTTP header being sent to the server.

API _removeHttpHeader(key)
Notes This will remove the key value pair in the HTTP header being sent to the server.

Eg.
 _removeHttpHeader("User-Agent");
This will remove the key “User-Agent” from the headers.

API _resetHttpHeader(key)
Notes This will reset the key value pair in the HTTP header being sent to the server.

Eg.
 _resetHttpHeader("User-Agent");
This will reset the key “User-Agent” in the headers.

API _setXHRReadyStatesToWaitFor($readyStates)
Notes Tells Sahi which AJAX ready states to wait for. By defaults Sahi waits for ready states 1, 2 and 3.
Eg.
_setXHRReadyStatesToWaitFor(2,3);
This will wait only for AJAX ready states 2 and 3, but not 1.

API _focusWindow()
Notes Brings the current window into focus above the other screens. Used with native events or screen shots. Currently works only on Windows.
Eg.
_focusWindow();
_takeScreenShot();
Related Sahi Callback Functions
Since Sahi Pro 4.3 (Build: 2012-08-05)

API _takeScreenShot()
Notes Takes a screen shot of the entire screen, and embeds image in reports. Use with _focusWindow to make sure the right window is in focus.
Eg.
_focusWindow();
_takeScreenShot();
Related Sahi Callback Functions
Since Sahi Pro 4.3 (Build: 2012-08-05)

API _takeSnapShot()
Notes Used to take a snapshot of a single step.

Functions available on browser only


API _savedRandom(key)
Notes Deprecated
Returns a previously saved random number agains that key. Details
Related _resetSavedRandom

API _getGlobal(key)
Notes Returns value stored against key. Details
Related _setGlobal




Functions available on proxy only


API _logException(exception)
Notes Logs an exception. Used in catch block of try-catch. Details

API _logExceptionAsFailure(exception)
Notes Logs an exception and stops execution. Used in catch block of try-catch. Details

API _stopOnError()
Notes Makes the script stop if an error occurs. This is the default behavior.

API _continueOnError()
Notes Makes script continue inspite of errors. Can be turned off with _stopOnError()

API _setRecovery(fn)
Notes Sets fn as recovery function. The function will be called before the script exists, if and only if there is a failure in the script. It can be turned off with _removeRecovery(). Details

API _removeRecovery(fn)
Notes Removes any recovery function which was set via _setRecovery. Details


  • Working with database

API _getDB(driver, jdbcurl, username, password)
Notes Returns a DB object which can be used to query the database. Details


  • Working with files

API _readFile(filePath)
Notes Reads a file at filePath and returns its contents as a string. Details

API _writeFile(text, filePath[, overwrite])
Notes Writes the text into file at filePath.
if overwrite is true, the file contents are overwritten.
Default is false which will append text at the end.

API _writeToFile(text, filePath[, overwrite])
Notes Same as _writeFile

API _readCSVFile(filePath, wordSeparator)
Notes Reads a csv file and returns a 2 dimensional array of the contents. If the separator between words is not a comma, it can be specified as the second parameter.

API _readExcelFile(filePath, sheetName,[true/false])
Notes Reads an Excel file and returns a 2 dimensional array of the contents. If the first row is not desired, the third parameter can be set to false. This will ignore the header.

API _getExcel(excelFilePath, sheetName)
Notes Allows manipulation of Excel files. This is a replacement of the older way of accessing excel sheets using _getDB.

API _writeCSVFile(array2d, filePath, overwrite, wordSeparator)
Notes Writes a 2 dimensional array into a file in CSV format, using the given wordSeparator (default is comma)

API _deleteFile(filePath)
Notes Deletes the file at filePath.

API _renameFile(oldFilePath, newFilePath)
Notes Renames (or moves) a given file from oldFilePath to newFilePath. If newFilePath already exists, it will be overwritten


  • Data driven testing

API _dataDrive(fn, data2DArray)
Notes Loops over data2DArray, and invokes function fn with each row of data. The invocation is within a try catch block with exception logging. More on data driven testing


  • Unit testing

API _runUnitTests()
Notes _runUnitTests() executes all functions whose name starts with "test". If functions setUp() and tearDown() are defined, they are executed before and after each test, irrespective of errors in the test functions.

Eg.
function setUp(){
  _log("In setUp");
}
function tearDown(){
  _log("In tearDown");
}
function testAddition() {
  _assertEqual(3, 1+2);
}
function testSubtraction() {
  _assertEqual(3, 5-2);
}
function testMultiplication() {
  _assertEqual(8, 2*4);
}
// Invoke all tests:
_runUnitTests();
// Invoke only testAddition and testMultiplication
// Use this for debugging when you are fixing just one test
// and don't want to run all the tests.
_runUnitTests(["testAddition", "testMultiplication"]);
Note that setUp() and tearDown() are called before and after EVERY testXXX method call.

  • Reading URL content


API_readURL(url)
NotesReads the content at the specified URL and returns its contents as a string


  • APIs for browser detection

API_isIE(), _isIE9()
NotesReturns true if browser is Internet Explorer

API_isFF(), _isFF2(), _isFF3(), _isFF4()
NotesReturns true if browser is Mozilla Firefox

API_isChrome()
NotesReturns true if browser is Google Chrome

API_isOpera()
NotesReturns true if browser is Opera

API_isSafari()
NotesReturns true if browser is Safari


  • APIs for controlling Report Logging






API_maskLogs($startMsg)
NotesStatements following _maskLogs($msg) will be masked in the logs. (A replacement text will be visible instead.) This is useful when password or other information should not be visible in logs. Masking can be toggled back using _unmaskLogs($endMsg). $startMsg and $endMsg are logged in the reports to help understand what has been masked.

Eg.

_maskLogs("Password Information start");
_setValue(_password("password"), "secret");
_unmaskLogs("Password Information end");

will output

maskLogs start: Password Information start [79 ms] [08:47:17.577]
message masked [35 ms] [08:47:17.612]
maskLogs end: Password Information end [66 ms] [08:47:17.678]

SinceSahi Pro V4.5


API_unmaskLogs($endMsg)
NotesToggles _maskLogs(). Re-enables normal report logging. $endMsg is visible in logs.
SinceSahi Pro V4.5


Browser Action APIs

Action APIs perform actions on the browser.

Since Sahi V2, Sahi executes Sahi scripts inside a Rhino Javascript engine in the proxy.
Actions which need to be performed on the browser are dispatched to the browser by the proxy.

The remarkable thing about these Browser Action APIs, is that the parameter expressions
passed to these APIs execute on the browser and not on the proxy.

Eg.
_click(document.form1.checkbox1) will work since document.form1.checkbox1 is evaluated on the browser.

Mouse actions

All mouse actions can be done with a combined keypress of a combo key. The values of combo are “CTRL”, “SHIFT”, “ALT” and “META”.

API _click(element, combo)
Notes Clicks the element. Details
API _rightClick(element, combo)
Notes Right clicks on the element. Details
API _doubleClick(element, combo)
Notes Double clicks on the element. Details
API _check(checkBoxOrRadioElement)
Notes Checks the given checkbox or radio element. If already checked, this API does not do anything.
API _uncheck(checkBoxElement)
Notes Unchecks the given checkbox. If already unchecked, this API does not do anything.
API _mouseOver(element, combo)
Notes Simulates a mouse over on the element. Details
API _mouseDown(element, isRight, combo)
Notes Simulates a mouse down on the element. Details
API _mouseUp(element, isRight, combo)
Notes Simulates a mouse up on the element.
API _dragDrop(elementToDrag, elementToDropOn)
Notes Drags elementToDrag and drops on elementToDropOn. Details
API _dragDropXY(elementToDrag, x, y[, isRelative])
Notes Drags elementToDrag and drops it on the given x, y coordinates.
If isRelative is true, drags x,y pixels relative to current position.
If isRelative is false, drags to x,y coordinate on browser. Details

Focus action

API _focus(element)
Notes Brings focus to element.
API _removeFocus(element)
Notes Removes focus from element.
API _blur(element)
Notes Removes focus from element.


Key actions

In the below APIs,
combo can be any of “CTRL”, “ALT”, “SHIFT” or “META
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)

Eg.

_keyPress(_textbox(“q”), [13,13]); // Press enter on textboxt “q”;

API _keyPress(element, charInfo, combo)
Notes Simulates a keypress event for key with given charInfo on the element. Refer above section for charInfo details. Details
API _keyDown(element, charInfo, combo)
Notes Simulates a keydown event for key with given charInfo on the element. Refer above section for charInfo details. Details
API _keyUp(element, charInfo, combo)
Notes Simulates a keyup event for key with given charInfo on the element. Refer above section for charInfo details. Details

Data input actions

API _setValue(element, text)
Notes Focuses on the element, types in the text and then removes focus from element.
element can be a textarea or a textbox. Details
API _setSelected(element, option_identifier, isMultiple)
Notes Selects the option with option_identifier in select element.
element can only be a select box.
isMultiple is used to select multiple values in a multi select box.
Details
API _setFile(element, filePath)
Notes Prepares the form to set file at filePath. Details
API _rteWrite(iframe, text)
Notes Writes text into a rich text editor based on content-editable iframe
API _type(element, text)
Notes Types the text into the element. Different from _setValue.
_type does not bring or remove focus from element. Rarely used.

Assertions

API _assertEqual(expected, actual, message)
Notes Asserts that expected and actual are equal, else logs the message. Details
API _assertNotEqual(expected, actual, message)
Notes Asserts that expected and actual are NOT equal, else logs the message. Details
API _assertNotNull(object, message)
Notes Asserts that the object is NOT null, else logs the message. Details
API _assertNull(object, message)
Notes Asserts that the object is null, else logs the message. Details
API _assertTrue(condition, message)
Notes Asserts that the condition is true, else logs the message. Details
API _assert(condition, message)
Notes Same as _assertTrue
API _assertNotTrue(condition, message)
Notes Asserts that the condition is NOT true, else logs the message. Details
API _assertFalse(condition, message)
Notes Asserts that the condition is false, else logs the message. Details
API _assertExists(object, message)
Notes Asserts that the object is not null, else logs the message.
API _assertNotExists(object, message)
Notes Asserts that the object does not exist (is null), else logs the message.
API _assertContainsText(expectedText, object, message)
Notes Asserts that the object contains the expectedText, else logs the message. Details
API _assertNotContainsText(expectedText, object, message)
Notes Asserts that the object does not contain the expectedText, else logs the message.
API _assertEqualArrays(expected, actual, message)
Notes Deprecated: Asserts that expected and actual arrays are equal, else logs the message.
This is internally called by _assertEqual if expected and actual are arrays.

Generic actions

API _simulateEvent(element, event)
Notes Used to simulate an event on element. Buggy (as of 21 May 2009). Will be modified.

Utility actions

API _navigateTo(url, forceReload)
Notes Navigates to the given url.
If the url is same as what is loaded on the browser, the page will be refreshed only if forceReload is true
Details
API _closeWindow()
Notes Closes the current window.
This will work only for popups.
Eg. _popup(“popWin”)._closeWindow();
API _closeBrowser()
Notes Closes the browser in the middle of a script.




API _openBrowser()
Notes Opens a browser in the middle of a script.

API _log(message, logLevel)
Notes Logs message into the playback logs.
logLevel can be “info”, “success”, “error”, “failure” and “custom1” through “custom5”
Details
API _wait(timeInMilliseconds, condition)
Notes Waits for timeInMilliseconds ms or till the condition is satisfied on the browser,
which ever is sooner. Details



API _setFlexReadyCondition()
Notes Defines some conditions to be fulfilled before performing actions on a flex application.

API _call(javascriptSnippet)
Notes Executes the javascriptSnippet on the browser, instead of in the Rhino engine. Details
API _setXHRReadyStatesToWaitFor($readyStates)
Notes Sets the AJAX ready states for which Sahi should wait.
API _eval(string)
Notes Evals the string on the browser, instead of in the Rhino engine. Details
API _execute(command[, isSynchronous])
Notes Executes any server side command that needs to be invoked via the command line or shell.
Useful for invoking other programs.
If isSynchronous is true, the function will wait till the command finishes. Details
API _callServer()
Notes Deprecated.
Calls server side code which cannnot be executed by javascript on the browser. Details
With Sahi V2, these actions can directly be performed by calling java classes from javascript through Rhino. Details
API _resetSavedRandom(key)
Notes Resets the random number associated with key, to another random number. Details
Deprecated. From Sahi V2, random numbers can be generated using _random and stored as simple variables.
Related _savedRandom , _random
API _setGlobal(key, value)
Notes Stores the value in key for retreival.
The value persists across tests in a suite, if suite.global_variables is true in sahi.properties.
Eg. _setGlobal(“userid1”, _textbox(“user”).value);
Related _getGlobal
API _set($variableName, value)
Notes Used to fetch the value of a page dependent variable (something that is part of the browser page) and store it in a Sahi variable. Details
Eg. _set($href, _link(“my link”).href);
API _fetch(element.value)
Notes Used to fetch the value of a page dependent variable (something that is part of the browser page) and store it in a Sahi variable.
Eg. var $text = _fetch(_textbox(“t1”).value);
API _count(apiType, id, inEl)
Notes Counts all elements of a particular type and stores them in a variable.
Eg. var $c = _count (”_link”, “/group 1/”);
API _collect(apiType, id, inEl)
Notes Collects all elements of a particular type and stores them in an array.
Eg. var $els = _collect (”_link”, “/group 1/”, _in(_div(“div1”)));

Actions to mock out particular URLs

API _addMock(pattern[, clazz_method])
Notes Forces the proxy to process certain patterns of urls differently.
If clazz_method is not specified, sends back a simple HTML blank page.
Details
API _mockImage(pattern[, clazz_method])
Notes Similar to _addMock, but by default sends back an image. Details
API _removeMock(pattern)
Notes Removes the mock behavior added via _addMock or _mockImage for that pattern. Details

Actions to set expectations for javascript confirms and prompts

API _expectConfirm(message, boolean)
Notes Sets an expectation such that when a javascript confirm with given message appears,
based on the boolean value, OK or Cancel will be processed. Details
API _expectPrompt(message, text)
Notes Sets an expectation such that when a javascript prompt with given message appears,
the given text is populated. Details
API _clearPrintCalled()
Notes resets the value of _printCalled
API _clearLastAlert()
Notes Clears the value returned by _lastAlert().
API _clearLastPrompt()
Notes Clears the value returned by _lastPrompt().
API _clearLastConfirm()
Notes Clears the value returned by _lastConfirm().

Actions used for debugging

API _highlight(element)
Notes Highlights an element with a red border. Used for debugging purposes.
API _alert(message)
Notes Brings up a javascript alert with given message. Use only while debugging
API _prompt(message)
Notes Brings up a javascript prompt with given message. Use only while debugging
API _confirm(message)
Notes Brings up a javascript confirm with given message. Use only while debugging
API _debug(message)
Notes Prints the message on to the console for debugging purposes.
API _debugToErr(message)
Notes Prints the message on to the error stream for debugging purposes.
API _debugToFile(message, filePath)
Notes Prints the message into a file for debugging purposes.

Toggle KeepAlive Actions

API _enableKeepAlive()
Notes Details
API _disableKeepAlive()
Notes Details

Cookie related actions

Also look at _cookie

API _createCookie(name, value, days)
Notes Creates a cookie with name and value which will expire in given days.
Details
API _deleteCookie(name)
Notes Deletes cookie with given name.
Details

Print related actions

API _clearPrintCalled()
Notes resets the value of _printCalled

Download related actions

Sahi handles file downloads by silently downloading files into sahi/temp/download folder.
The last downloaded file can be manipulated by the following APIs.
Note that a _wait() statement may be required before _saveDownloadedAs in case the file is big and takes a lot of time to download.

More Details

API _saveDownloadedAs(filePath)
Notes Saves the file which was downloaded into sahi/temp/folder into the given filePath
API _clearLastDownloadedFileName()
Notes Clears the _lastDownloadedFileName (so that new files downloaded with the same fileName can be asserted)
Related _lastDownloadedFileName

---


Top Rounds