SelBlocks 2.1Edit



Provides Selenium commands with JavaScript conditionals, looping, callable functions, error catching, and JSON/XML driven parameterization.


  • Provides the following control structures: if/elseIf/else, try/catch/finally/throw, for/foreach/while, continue/break, call/function/return, loadXmlVars/loadJsonVars, forXml/forJson, exitTest
  • Function and loop parameters use regular Selenium variables that are local to the block, overriding variables of the same name, and that are restored when the block exits.
  • Command parameters are JavaScript expressions that are evaluated with Selenium variables in scope, which can therefore be referenced by their simple names, e.g.: i+1
  • Variables can be configured via external XML and/or JSON files.
  • A function definition can appear anywhere, (they are skipped over in normal execution flow).
  • Functions can be called recursively.

Examples of UseEdit

Note that Selenium performs variable substitution before each command executes. When Selenium variables are used in SelBlocks parameters, which are JavaScript expressions, they are evaluated as literals. So for example, you would write: '$(userid}'. Or more simply: userid.

    getEval|"${userid}, our hero");
    getEval|"${userid}, the villain");
for|i=1; i <= 10; i++
  getEval|"${userid}: ${role}");
-- log odd numbers from 0 to 10
for|i=0; i <= 100; i++
-- extravagant example, but demonstrates possibilities of functions
getEval|"this will NOT execute");
getEval|"this WILL execute");
getEval|"this will NOT execute");
getEval|"this will NOT execute");
getEval|"this and any following commands will NOT execute");

Sample varset.xml:

  <vars userid="dilbert" role="superuser" />
  <vars userid="wally"   role="lazyuser" />

Sample varset.json:

  { userid: "dilbert", role: "superuser" }
 ,{ userid: "wally",   role: "lazyuser" }

Note that if a data file is in the same directory as the invoking test script, then a relative file path can be used.

try/catch/finally blocksEdit

Try can provide special handling when an error is thrown, and can guarantee execution of, for example, "cleanup" logic.

A catch block specifies what to do if an error is thrown in the try block. That is, if any statement within the try block, or in a function or sub-function called from within the try block, throws an error, then control jumps to the matching catch block, and the error is cleared. If no error is thrown in the try block, then the catch block is skipped. Catch intercepts a given error by matching on its error message, which is specified as a "substring", or as a /regular expression/. Providing no specification will catch all errors.

A finally block executes after the try and catch blocks. It always executes regardless of whether or not an error is thrown or caught. It executes even if the try or catch block concludes via "flow change" commands: continue, break, return, or exitTest commands.

Try blocks can be nested. If an inner try does not catch an error, the enclosing try/catch is entered. The contents of all nested finally block(s) are guaranteed to execute, innermost to outermost - again, even if error(s) occur along the way.

Both catch and finally are optional, but if neither is provided then the try simply has no effect.

An optional identifier may be specified on try and endTry, which will be validated for proper pairing.

Example of try/catch/finallyEdit

    getEval|alert("this alert will NOT get executed")

Automatic VariablesEdit

SelBlocks provides automatic variables in three situations:

  • Inside a foreach or endForeach loop, ${_i} holds the zero-based index of the loop iteration.
  • When a function terminates via the return command, ${_result} holds the result value.
  • When an error is caught by a catch, ${_error} holds the caught error object.

These variables can of course be referenced by SelBlocks command arguments as simply: _i, _result and _error.

JavaScript ExtensionsEdit

These can be used in SelBlocks expressions:

String.isOneOf : Example: if|employee.isOneOf("dilbert","wally","ratbert")
String.mapTo : Example: if|employee.mapTo("peon", ["dilbert","wally"]) == "peon"
String.translate : Example: if|employee.translate("e", "3"]) == "p3on"
$e(locator) : Example: $e("link=SelBlocks review")
$x(xpath) : Example: $x("//input[@id=(//label[.='User ID']/@for)]")

Function ReferenceEdit

Function Description
$e(locator) Retrieve the specified HTML element. Returns the first if there are multiple matches.
$x(xpath, context-xpath, resultType) Retrieve the specified value/element. Returns the first value/element if there are multiple matches.

The optional context-xpath constrains the match to within the specified region, rather than the entire document.

$X(xpath, context-xpath, resultType) Retrieve the specified values/elements as an array.

The optional context-xpath constrains the match to within the specified region, rather than the entire document.

Command ReferenceEdit

Command Target Value Description
if conditional If the conditional evaluates to true, continue into the body of the if.
elseIf conditional If the conditional evaluates to true, continue into the body of the elseIf.
else If the previous if/elseIf block has executed, skip to the endIf.
endIf Marks the end of an if block.
goto label Jump to the given label.
gotoIf conditional label If the conditional evaluates to true, jump to the given label.
label Serves as the target for goto/gotoIf statements.
skipNext ?number-of-lines (default is 1) Skips over the specified number of lines.
try ?try-name Defines a section with error handling, and/or guaranteed execution of "cleanup" logic.
catch regular-expression or substring Defines a block to be executed when an error is thrown in the try block.
finally Defines a block that is guaranteed to be executed, whether any error occurs or not.
endTry ?try-name Marks the end of a try block.
throw error-message Throws the specified error.
for initializer; conditional; incrementer Perform the initializer. Then iterate over the block of code until the conditional evaluates to false, performing the incrementer after each iteration.
endFor Marks the end of a for block.
foreach var-name comma-separated-values Iterate a block of code, once for each value.
endForeach Marks the end of a foreach block.
while conditional Iterate a block of code until the conditional evaluates to false.
endWhile Marks the end of a while block.
continue ?conditional Cause execution within a loop to immediately begin the next iteration.
break ?conditional Cause execution within a loop to immediately exit.
call function-name ?comma-separated-arguments Execute the named function, then continue on to the next step in the script.
function function-name Defines a callable function.
return ?value Immediately terminate a function, and return the optional value.
endFunction function-name Marks the end of a function block.
loadXmlVars file-path ?selector-expression Create the set of Selenium variable(s) as defined by the XML file.
loadJsonVars file-path ?selector-expression Create the set of Selenium variable(s) as defined by the JSON file.
forXml xml-filepath Iterate a block of code, once for each set of value(s) provided by the XML file.
endForXml Marks the end of a forXml block.
forJson json-filepath Iterate a block of code, once for each set of value(s) provided by the JSON file.
endForJson Marks the end of a forJson block.
exitTest Causes the current test to immediately end.

Automatic Variable ReferenceEdit

Name Context
_i foreach
_result return
_error catch



Note that the Stored Variables Viewer addon will display the values of SelBlocks parameters, because they are implemented as regular Selenium variables. The only thing special about SelBlocks parameters is that they are activated and deactivated, (added and removed), as execution flows into and out of blocks, eg, for, endFor, function, endFunction, etc. So this can provide a convenient way to monitor the progress of an executing test script.

Selenium ServerEdit

Sorry, this feature has a significant bug, and is not currently supported.

Selenese scripts that use SelBlocks commands can also be run in Selenium Server via the -user-extensions and -htmlSuite options. Get the current user-extensions.js here:

For more information on running Selenium Server, see:

Note that prior to version 2.1 SelBlocks has been a Firefox extension only, whereas Selenium Server can target a wide range of browsers. SelBlocks currently passes its full regression test suite when run against:

  • firefox (31.4)
  • googlechrome (40.0)
  • opera (27.0)

Community help is welcome and encouraged in expanding this list. There are currently known issues with:

  • iexplorer (11.0): Object.defineProperties fails - test-startup hangs
  • safari (5.1.7): htmlTestRunner is not defined - test-startup hangs

Running scripts in Selenium Server introduces the possibilty of browser compatibility issues, especially when running IDE-produced scripts against non-Firefox browsers. Potential pain points include differen ces in JavaScript error messaging, (e.g., expectError), and XPath capabilities, ($x() and $X()).

When reporting an issue, be sure to provide very specific browser/OS info, as well as the faling test case, test html, and error log. Better yet, if you can fix the problem, submit a github pull request -- which is how server support came about in the first place. A big thanks to Matthew Kastor for this contribution!

For an overview of how the SelBlocks user extension works, see:


SelBlocks is compatible with most other Selenium plugins. The only known exceptions are misbehaving plugins, and direct derivatives of SelBlocks itself:

  • SelBlocks is not compatible with flowControl, because that plugin directly modifies an internal Selenium pointer, which prevents any other plugins from doing intitialization before tests run. Note however that SelBlocks does provide equivalent commands, and is generally a plug-compatible replacement.
  • SelBlocks is not compatible with SelBlocks Global, which is a code fork of SelBlocks, and therefore tries to define the very same command extensions.


You cannot call a Selblocks function that is defined in another Selenium script.

You cannot use Set Start Point in the IDE to begin execution in the middle of an if, for, try, or function. This is because each kind of block maintains context during its execution that is initialized when that block is entered from the top. Jumping into the middle of a block has undefined behavior.

Local file access is not supported by Selenium Server. This could be problematic for commands like loadJsonVars, loadXmlVars, forJson and forXml. However, files can be accessed via http.

Never use the ...AndWait counterpart of a SelBlocks command, e.g., ifAndWait. (Selenium automatically registers one with every defined command, even though it does not always make sense.) If you use one of these, (usually via inadvertent auto-completion), SelBlocks will throw an error when you try to start the script in the IDE.

This is a bit more difficult to diagnose in Selenium Server, which cannot currently detect the situation, and therefore simply hangs without an error when such a command executes.

Philosophical NoteEdit

I tend to agree, in principle, with Dan Fabulich's view on keeping HTML Selenese simple. But in practice you're able to maintain MUCH simpler scripts by using some if/else and looping. Note that there is no language translation for SelBlocks commands, so they're commented-out in exported test scripts. Although hand-translation in the target language ought to be pretty straightforward. I would just say, use these constructs judiciously.

Revision HistoryEdit

  • 2015-02-12: v2.1
    • Enhancement #10 Added support for Selenium Server. (A big thanks to Matthew Kastor for this contribution)
    • Added ability to catch verify command failures
    • Fixed Issue #6 Try/catch not clearing error status
    • Fixed Issue #11 Top-level try/finally leaves Selenium IDE in running mode
    • Fixed Issue #12 Unhandled try/catch in one test affects next test
  • 2013-10-28: v2.0.1
    • Added checking for multiple un-terminated blocks
    • Moved overview info from selblocks.js to the about dialog
    • Added smoketest script for Mozilla reviewers
  • 2013-10-28: v2.0
    • Added elseIf and try/catch/finally/throw commands
    • Improved validation of command expressions
    • Block boundaries are now enforced (prevent jumping in-to and/or out-of blocks)
    • Deprecates script/endScript, instead use function/endFunction
    • Implicit initialization of for loop variable(s):
      for|i=1;i<=10;i++|i becomes just for|i=1;i<=10;i++
  • 2013-09-08: v1.5
    • Added loadJsonVars and forJson
    • Made parameter expressions for robust
  • 2013-07-28: v1.3.1
    • Firefox 4+ compatibility
  • 2011-08-14: v1.3
  • 2011-08-05: v1.2
  • 2011-04-10: v1.1
  • 2011-03-28: v1.0

All versions: