2
* Copyright 2004 ThoughtWorks, Inc
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
8
* http://www.apache.org/licenses/LICENSE-2.0
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
18
// TODO: stop navigating this.browserbot.document() ... it breaks encapsulation
20
var storedVars = new Object();
22
function Selenium(browserbot) {
24
* Defines an object that runs Selenium commands.
26
* <h3><a name="locators"></a>Element Locators</h3>
28
* Element Locators tell Selenium which HTML element a command refers to.
29
* The format of a locator is:</p>
31
* <em>locatorType</em><strong>=</strong><em>argument</em>
35
* We support the following strategies for locating elements:
39
* <li><strong>identifier</strong>=<em>id</em>:
40
* Select the element with the specified @id attribute. If no match is
41
* found, select the first element whose @name attribute is <em>id</em>.
42
* (This is normally the default; see below.)</li>
43
* <li><strong>id</strong>=<em>id</em>:
44
* Select the element with the specified @id attribute.</li>
46
* <li><strong>name</strong>=<em>name</em>:
47
* Select the first element with the specified @name attribute.
48
* <ul class="first last simple">
50
* <li>name=username</li>
53
* <p>The name may optionally be followed by one or more <em>element-filters</em>, separated from the name by whitespace. If the <em>filterType</em> is not specified, <strong>value</strong> is assumed.</p>
55
* <ul class="first last simple">
56
* <li>name=flavour value=chocolate</li>
59
* <li><strong>dom</strong>=<em>javascriptExpression</em>:
61
* Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object
62
* Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block.
63
* <ul class="first last simple">
64
* <li>dom=document.forms['myForm'].myDropdown</li>
65
* <li>dom=document.images[56]</li>
66
* <li>dom=function foo() { return document.links[1]; }; foo();</li>
71
* <li><strong>xpath</strong>=<em>xpathExpression</em>:
72
* Locate an element using an XPath expression.
73
* <ul class="first last simple">
74
* <li>xpath=//img[@alt='The image alt text']</li>
75
* <li>xpath=//table[@id='table1']//tr[4]/td[2]</li>
76
* <li>xpath=//a[contains(@href,'#id1')]</li>
77
* <li>xpath=//a[contains(@href,'#id1')]/@class</li>
78
* <li>xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td</li>
79
* <li>xpath=//input[@name='name2' and @value='yes']</li>
80
* <li>xpath=//*[text()="right"]</li>
84
* <li><strong>link</strong>=<em>textPattern</em>:
85
* Select the link (anchor) element which contains text matching the
86
* specified <em>pattern</em>.
87
* <ul class="first last simple">
88
* <li>link=The link text</li>
93
* <li><strong>css</strong>=<em>cssSelectorSyntax</em>:
94
* Select the element using css selectors. Please refer to <a href="http://www.w3.org/TR/REC-CSS2/selector.html">CSS2 selectors</a>, <a href="http://www.w3.org/TR/2001/CR-css3-selectors-20011113/">CSS3 selectors</a> for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package.
95
* <ul class="first last simple">
96
* <li>css=a[href="#id3"]</li>
97
* <li>css=span#firstChild + span</li>
99
* <p>Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after). </p>
104
* Without an explicit locator prefix, Selenium uses the following default
108
* <ul class="simple">
109
* <li><strong>dom</strong>, for locators starting with "document."</li>
110
* <li><strong>xpath</strong>, for locators starting with "//"</li>
111
* <li><strong>identifier</strong>, otherwise</li>
114
* <h3><a name="element-filters">Element Filters</a></h3>
116
* <p>Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator.</p>
117
* <p>Filters look much like locators, ie.</p>
119
* <em>filterType</em><strong>=</strong><em>argument</em></blockquote>
121
* <p>Supported element-filters are:</p>
122
* <p><strong>value=</strong><em>valuePattern</em></p>
124
* Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons.</blockquote>
125
* <p><strong>index=</strong><em>index</em></p>
127
* Selects a single element based on its position in the list (offset from zero).</blockquote>
130
* <h3><a name="patterns"></a>String-match Patterns</h3>
133
* Various Pattern syntaxes are available for matching string values:
136
* <li><strong>glob:</strong><em>pattern</em>:
137
* Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a
138
* kind of limited regular-expression syntax typically used in command-line
139
* shells. In a glob pattern, "*" represents any sequence of characters, and "?"
140
* represents any single character. Glob patterns match against the entire
142
* <li><strong>regexp:</strong><em>regexp</em>:
143
* Match a string using a regular-expression. The full power of JavaScript
144
* regular-expressions is available.</li>
145
* <li><strong>exact:</strong><em>string</em>:
147
* Match a string exactly, verbatim, without any of that fancy wildcard
151
* If no pattern prefix is specified, Selenium assumes that it's a "glob"
155
this.browserbot = browserbot;
156
this.optionLocatorFactory = new OptionLocatorFactory();
157
// DGF for backwards compatibility
158
this.page = function() {
161
this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
162
this.mouseSpeed = 10;
165
Selenium.DEFAULT_TIMEOUT = 30 * 1000;
166
Selenium.DEFAULT_MOUSE_SPEED = 10;
168
Selenium.decorateFunctionWithTimeout = function(f, timeout) {
172
var timeoutValue = parseInt(timeout);
173
if (isNaN(timeoutValue)) {
174
throw new SeleniumError("Timeout is not a number: '" + timeout + "'");
176
var now = new Date().getTime();
177
var timeoutTime = now + timeoutValue;
179
if (new Date().getTime() > timeoutTime) {
180
throw new SeleniumError("Timed out after " + timeoutValue + "ms");
186
Selenium.createForWindow = function(window, proxyInjectionMode) {
187
if (!window.location) {
188
throw "error: not a window!";
190
return new Selenium(BrowserBot.createForWindow(window, proxyInjectionMode));
193
Selenium.prototype.reset = function() {
194
this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
195
// todo: this.browserbot.reset()
196
this.browserbot.selectWindow("null");
197
this.browserbot.resetPopups();
200
Selenium.prototype.doClick = function(locator) {
202
* Clicks on a link, button, checkbox or radio button. If the click action
203
* causes a new page to load (like a link usually does), call
206
* @param locator an element locator
209
var element = this.browserbot.findElement(locator);
210
this.browserbot.clickElement(element);
213
Selenium.prototype.doDoubleClick = function(locator) {
215
* Double clicks on a link, button, checkbox or radio button. If the double click action
216
* causes a new page to load (like a link usually does), call
219
* @param locator an element locator
222
var element = this.browserbot.findElement(locator);
223
this.browserbot.doubleClickElement(element);
226
Selenium.prototype.doClickAt = function(locator, coordString) {
228
* Clicks on a link, button, checkbox or radio button. If the click action
229
* causes a new page to load (like a link usually does), call
232
* @param locator an element locator
233
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
234
* event relative to the element returned by the locator.
237
var element = this.browserbot.findElement(locator);
238
var clientXY = getClientXY(element, coordString)
239
this.browserbot.clickElement(element, clientXY[0], clientXY[1]);
242
Selenium.prototype.doDoubleClickAt = function(locator, coordString) {
244
* Doubleclicks on a link, button, checkbox or radio button. If the action
245
* causes a new page to load (like a link usually does), call
248
* @param locator an element locator
249
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
250
* event relative to the element returned by the locator.
253
var element = this.browserbot.findElement(locator);
254
var clientXY = getClientXY(element, coordString)
255
this.browserbot.doubleClickElement(element, clientXY[0], clientXY[1]);
258
Selenium.prototype.doFireEvent = function(locator, eventName) {
260
* Explicitly simulate an event, to trigger the corresponding "on<em>event</em>"
263
* @param locator an <a href="#locators">element locator</a>
264
* @param eventName the event name, e.g. "focus" or "blur"
266
var element = this.browserbot.findElement(locator);
267
triggerEvent(element, eventName, false);
270
Selenium.prototype.doKeyPress = function(locator, keySequence) {
272
* Simulates a user pressing and releasing a key.
274
* @param locator an <a href="#locators">element locator</a>
275
* @param keySequence Either be a string("\" followed by the numeric keycode
276
* of the key to be pressed, normally the ASCII value of that key), or a single
277
* character. For example: "w", "\119".
279
var element = this.browserbot.findElement(locator);
280
triggerKeyEvent(element, 'keypress', keySequence, true,
281
this.browserbot.controlKeyDown,
282
this.browserbot.altKeyDown,
283
this.browserbot.shiftKeyDown,
284
this.browserbot.metaKeyDown);
287
Selenium.prototype.doShiftKeyDown = function() {
289
* Press the shift key and hold it down until doShiftUp() is called or a new page is loaded.
292
this.browserbot.shiftKeyDown = true;
295
Selenium.prototype.doShiftKeyUp = function() {
297
* Release the shift key.
300
this.browserbot.shiftKeyDown = false;
303
Selenium.prototype.doMetaKeyDown = function() {
305
* Press the meta key and hold it down until doMetaUp() is called or a new page is loaded.
308
this.browserbot.metaKeyDown = true;
311
Selenium.prototype.doMetaKeyUp = function() {
313
* Release the meta key.
316
this.browserbot.metaKeyDown = false;
319
Selenium.prototype.doAltKeyDown = function() {
321
* Press the alt key and hold it down until doAltUp() is called or a new page is loaded.
324
this.browserbot.altKeyDown = true;
327
Selenium.prototype.doAltKeyUp = function() {
329
* Release the alt key.
332
this.browserbot.altKeyDown = false;
335
Selenium.prototype.doControlKeyDown = function() {
337
* Press the control key and hold it down until doControlUp() is called or a new page is loaded.
340
this.browserbot.controlKeyDown = true;
343
Selenium.prototype.doControlKeyUp = function() {
345
* Release the control key.
348
this.browserbot.controlKeyDown = false;
351
Selenium.prototype.doKeyDown = function(locator, keySequence) {
353
* Simulates a user pressing a key (without releasing it yet).
355
* @param locator an <a href="#locators">element locator</a>
356
* @param keySequence Either be a string("\" followed by the numeric keycode
357
* of the key to be pressed, normally the ASCII value of that key), or a single
358
* character. For example: "w", "\119".
360
var element = this.browserbot.findElement(locator);
361
triggerKeyEvent(element, 'keydown', keySequence, true,
362
this.browserbot.controlKeyDown,
363
this.browserbot.altKeyDown,
364
this.browserbot.shiftKeyDown,
365
this.browserbot.metaKeyDown);
368
Selenium.prototype.doKeyUp = function(locator, keySequence) {
370
* Simulates a user releasing a key.
372
* @param locator an <a href="#locators">element locator</a>
373
* @param keySequence Either be a string("\" followed by the numeric keycode
374
* of the key to be pressed, normally the ASCII value of that key), or a single
375
* character. For example: "w", "\119".
377
var element = this.browserbot.findElement(locator);
378
triggerKeyEvent(element, 'keyup', keySequence, true,
379
this.browserbot.controlKeyDown,
380
this.browserbot.altKeyDown,
381
this.browserbot.shiftKeyDown,
382
this.browserbot.metaKeyDown);
385
function getClientXY(element, coordString) {
391
coords = coordString.split(/,/);
392
x = Number(coords[0]);
393
y = Number(coords[1]);
399
// Get position of element,
400
// Return 2 item array with clientX and clientY
401
return [Selenium.prototype.getElementPositionLeft(element) + x, Selenium.prototype.getElementPositionTop(element) + y];
404
Selenium.prototype.doMouseOver = function(locator) {
406
* Simulates a user hovering a mouse over the specified element.
408
* @param locator an <a href="#locators">element locator</a>
410
var element = this.browserbot.findElement(locator);
411
this.browserbot.triggerMouseEvent(element, 'mouseover', true);
414
Selenium.prototype.doMouseOut = function(locator) {
416
* Simulates a user moving the mouse pointer away from the specified element.
418
* @param locator an <a href="#locators">element locator</a>
420
var element = this.browserbot.findElement(locator);
421
this.browserbot.triggerMouseEvent(element, 'mouseout', true);
424
Selenium.prototype.doMouseDown = function(locator) {
426
* Simulates a user pressing the mouse button (without releasing it yet) on
427
* the specified element.
429
* @param locator an <a href="#locators">element locator</a>
431
var element = this.browserbot.findElement(locator);
432
this.browserbot.triggerMouseEvent(element, 'mousedown', true);
435
Selenium.prototype.doMouseDownAt = function(locator, coordString) {
437
* Simulates a user pressing the mouse button (without releasing it yet) on
438
* the specified element.
440
* @param locator an <a href="#locators">element locator</a>
441
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
442
* event relative to the element returned by the locator.
444
var element = this.browserbot.findElement(locator);
445
var clientXY = getClientXY(element, coordString)
447
this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientXY[0], clientXY[1]);
450
Selenium.prototype.doMouseUp = function(locator) {
452
* Simulates a user pressing the mouse button (without releasing it yet) on
453
* the specified element.
455
* @param locator an <a href="#locators">element locator</a>
457
var element = this.browserbot.findElement(locator);
458
this.browserbot.triggerMouseEvent(element, 'mouseup', true);
461
Selenium.prototype.doMouseUpAt = function(locator, coordString) {
463
* Simulates a user pressing the mouse button (without releasing it yet) on
464
* the specified element.
466
* @param locator an <a href="#locators">element locator</a>
467
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
468
* event relative to the element returned by the locator.
470
var element = this.browserbot.findElement(locator);
471
var clientXY = getClientXY(element, coordString)
473
this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientXY[0], clientXY[1]);
476
Selenium.prototype.doMouseMove = function(locator) {
478
* Simulates a user pressing the mouse button (without releasing it yet) on
479
* the specified element.
481
* @param locator an <a href="#locators">element locator</a>
483
var element = this.browserbot.findElement(locator);
484
this.browserbot.triggerMouseEvent(element, 'mousemove', true);
487
Selenium.prototype.doMouseMoveAt = function(locator, coordString) {
489
* Simulates a user pressing the mouse button (without releasing it yet) on
490
* the specified element.
492
* @param locator an <a href="#locators">element locator</a>
493
* @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
494
* event relative to the element returned by the locator.
497
var element = this.browserbot.findElement(locator);
498
var clientXY = getClientXY(element, coordString)
500
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientXY[0], clientXY[1]);
503
Selenium.prototype.doType = function(locator, value) {
505
* Sets the value of an input field, as though you typed it in.
507
* <p>Can also be used to set the value of combo boxes, check boxes, etc. In these cases,
508
* value should be the value of the option selected, not the visible text.</p>
510
* @param locator an <a href="#locators">element locator</a>
511
* @param value the value to type
513
if (this.browserbot.controlKeyDown || this.browserbot.altKeyDown || this.browserbot.metaKeyDown) {
514
throw new SeleniumError("type not supported immediately after call to controlKeyDown() or altKeyDown() or metaKeyDown()");
516
// TODO fail if it can't be typed into.
517
var element = this.browserbot.findElement(locator);
518
if (this.browserbot.shiftKeyDown) {
519
value = new String(value).toUpperCase();
521
this.browserbot.replaceText(element, value);
524
Selenium.prototype.doTypeKeys = function(locator, value) {
526
* Simulates keystroke events on the specified element, as though you typed the value key-by-key.
528
* <p>This is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string;
529
* this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events.</p>
531
* <p>Unlike the simple "type" command, which forces the specified value into the page directly, this command
532
* may or may not have any visible effect, even in cases where typing keys would normally have a visible effect.
533
* For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in
535
* <p>In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to
536
* send the keystroke events corresponding to what you just typed.</p>
538
* @param locator an <a href="#locators">element locator</a>
539
* @param value the value to type
541
var keys = new String(value).split("");
542
for (var i = 0; i < keys.length; i++) {
544
this.doKeyDown(locator, c);
545
this.doKeyUp(locator, c);
546
this.doKeyPress(locator, c);
550
Selenium.prototype.doSetSpeed = function(value) {
552
* Set execution speed (i.e., set the millisecond length of a delay which will follow each selenium operation). By default, there is no such delay, i.e.,
553
* the delay is 0 milliseconds.
555
* @param value the number of milliseconds to pause after operation
557
throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
560
Selenium.prototype.doGetSpeed = function() {
562
* Get execution speed (i.e., get the millisecond length of the delay following each selenium operation). By default, there is no such delay, i.e.,
563
* the delay is 0 milliseconds.
567
throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
570
Selenium.prototype.findToggleButton = function(locator) {
571
var element = this.browserbot.findElement(locator);
572
if (element.checked == null) {
573
Assert.fail("Element " + locator + " is not a toggle-button.");
578
Selenium.prototype.doCheck = function(locator) {
580
* Check a toggle-button (checkbox/radio)
582
* @param locator an <a href="#locators">element locator</a>
584
this.findToggleButton(locator).checked = true;
587
Selenium.prototype.doUncheck = function(locator) {
589
* Uncheck a toggle-button (checkbox/radio)
591
* @param locator an <a href="#locators">element locator</a>
593
this.findToggleButton(locator).checked = false;
596
Selenium.prototype.doSelect = function(selectLocator, optionLocator) {
598
* Select an option from a drop-down using an option locator.
601
* Option locators provide different ways of specifying options of an HTML
602
* Select element (e.g. for selecting a specific option, or for asserting
603
* that the selected option satisfies a specification). There are several
604
* forms of Select Option Locator.
607
* <li><strong>label</strong>=<em>labelPattern</em>:
608
* matches options based on their labels, i.e. the visible text. (This
610
* <ul class="first last simple">
611
* <li>label=regexp:^[Oo]ther</li>
614
* <li><strong>value</strong>=<em>valuePattern</em>:
615
* matches options based on their values.
616
* <ul class="first last simple">
617
* <li>value=other</li>
622
* <li><strong>id</strong>=<em>id</em>:
624
* matches options based on their ids.
625
* <ul class="first last simple">
626
* <li>id=option1</li>
629
* <li><strong>index</strong>=<em>index</em>:
630
* matches an option based on its index (offset from zero).
631
* <ul class="first last simple">
638
* If no option locator prefix is provided, the default behaviour is to match on <strong>label</strong>.
642
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
643
* @param optionLocator an option locator (a label by default)
645
var element = this.browserbot.findElement(selectLocator);
646
if (!("options" in element)) {
647
throw new SeleniumError("Specified element is not a Select (has no options)");
649
var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
650
var option = locator.findOption(element);
651
this.browserbot.selectOption(element, option);
656
Selenium.prototype.doAddSelection = function(locator, optionLocator) {
658
* Add a selection to the set of selected options in a multi-select element using an option locator.
660
* @see #doSelect for details of option locators
662
* @param locator an <a href="#locators">element locator</a> identifying a multi-select box
663
* @param optionLocator an option locator (a label by default)
665
var element = this.browserbot.findElement(locator);
666
if (!("options" in element)) {
667
throw new SeleniumError("Specified element is not a Select (has no options)");
669
var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
670
var option = locator.findOption(element);
671
this.browserbot.addSelection(element, option);
674
Selenium.prototype.doRemoveSelection = function(locator, optionLocator) {
676
* Remove a selection from the set of selected options in a multi-select element using an option locator.
678
* @see #doSelect for details of option locators
680
* @param locator an <a href="#locators">element locator</a> identifying a multi-select box
681
* @param optionLocator an option locator (a label by default)
684
var element = this.browserbot.findElement(locator);
685
if (!("options" in element)) {
686
throw new SeleniumError("Specified element is not a Select (has no options)");
688
var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
689
var option = locator.findOption(element);
690
this.browserbot.removeSelection(element, option);
693
Selenium.prototype.doRemoveAllSelections = function(locator) {
695
* Unselects all of the selected options in a multi-select element.
697
* @param locator an <a href="#locators">element locator</a> identifying a multi-select box
699
var element = this.browserbot.findElement(locator);
700
if (!("options" in element)) {
701
throw new SeleniumError("Specified element is not a Select (has no options)");
703
for (var i = 0; i < element.options.length; i++) {
704
this.browserbot.removeSelection(element, element.options[i]);
708
Selenium.prototype.doSubmit = function(formLocator) {
710
* Submit the specified form. This is particularly useful for forms without
711
* submit buttons, e.g. single-input "Search" forms.
713
* @param formLocator an <a href="#locators">element locator</a> for the form you want to submit
715
var form = this.browserbot.findElement(formLocator);
716
return this.browserbot.submit(form);
720
Selenium.prototype.makePageLoadCondition = function(timeout) {
721
if (timeout == null) {
722
timeout = this.defaultTimeout;
724
return Selenium.decorateFunctionWithTimeout(fnBind(this._isNewPageLoaded, this), timeout);
727
Selenium.prototype.doOpen = function(url) {
729
* Opens an URL in the test frame. This accepts both relative and absolute
732
* The "open" command waits for the page to load before proceeding,
733
* ie. the "AndWait" suffix is implicit.
735
* <em>Note</em>: The URL must be on the same domain as the runner HTML
736
* due to security restrictions in the browser (Same Origin Policy). If you
737
* need to open an URL on another domain, use the Selenium Server to start a
738
* new browser session on that domain.
740
* @param url the URL to open; may be relative or absolute
742
this.browserbot.openLocation(url);
743
return this.makePageLoadCondition();
746
Selenium.prototype.doOpenWindow = function(url, windowID) {
748
* Opens a popup window (if a window with that ID isn't already open).
749
* After opening the window, you'll need to select it using the selectWindow
752
* <p>This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example).
753
* In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using
754
* an empty (blank) url, like this: openWindow("", "myFunnyWindow").</p>
756
* @param url the URL to open, which can be blank
757
* @param windowID the JavaScript window ID of the window to select
759
this.browserbot.openWindow(url, windowID);
762
Selenium.prototype.doSelectWindow = function(windowID) {
764
* Selects a popup window; once a popup window has been selected, all
765
* commands go to that window. To select the main window again, use null
768
* <p>Selenium has several strategies for finding the window object referred to by the "windowID" parameter.</p>
770
* <p>1.) if windowID is null, then it is assumed the user is referring to the original window instantiated by the browser).</p>
771
* <p>2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window, then it is assumed
772
* that this variable contains the return value from a call to the JavaScript window.open() method.</p>
773
* <p>3.) Otherwise, selenium looks in a hash it maintains that maps string names to window objects. Each of these string
774
* names matches the second parameter "windowName" past to the JavaScript method window.open(url, windowName, windowFeatures, replaceFlag)
775
* (which selenium intercepts).</p>
777
* <p>If you're having trouble figuring out what is the name of a window that you want to manipulate, look at the selenium log messages
778
* which identify the names of windows created via window.open (and therefore intercepted by selenium). You will see messages
779
* like the following for each window as it is opened:</p>
781
* <p><code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"</code></p>
783
* <p>In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example).
784
* (This is bug SEL-339.) In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using
785
* an empty (blank) url, like this: openWindow("", "myFunnyWindow").</p>
787
* @param windowID the JavaScript window ID of the window to select
789
this.browserbot.selectWindow(windowID);
792
Selenium.prototype.doSelectFrame = function(locator) {
794
* Selects a frame within the current window. (You may invoke this command
795
* multiple times to select nested frames.) To select the parent frame, use
796
* "relative=parent" as a locator; to select the top frame, use "relative=top".
798
* <p>You may also use a DOM expression to identify the frame you want directly,
799
* like this: <code>dom=frames["main"].frames["subframe"]</code></p>
801
* @param locator an <a href="#locators">element locator</a> identifying a frame or iframe
803
this.browserbot.selectFrame(locator);
806
Selenium.prototype.getLogMessages = function() {
808
* Return the contents of the log.
810
* <p>This is a placeholder intended to make the code generator make this API
811
* available to clients. The selenium server will intercept this call, however,
812
* and return its recordkeeping of log messages since the last call to this API.
813
* Thus this code in JavaScript will never be called.</p>
815
* <p>The reason I opted for a servercentric solution is to be able to support
816
* multiple frames served from different domains, which would break a
817
* centralized JavaScript logging mechanism under some conditions.</p>
819
* @return string all log messages seen since the last call to this API
821
return "getLogMessages should be implemented in the selenium server";
825
Selenium.prototype.getWhetherThisFrameMatchFrameExpression = function(currentFrameString, target) {
827
* Determine whether current/locator identify the frame containing this running code.
829
* <p>This is useful in proxy injection mode, where this code runs in every
830
* browser frame and window, and sometimes the selenium server needs to identify
831
* the "current" frame. In this case, when the test calls selectFrame, this
832
* routine is called for each frame to figure out which one has been selected.
833
* The selected frame will return true, while all others will return false.</p>
835
* @param currentFrameString starting frame
836
* @param target new frame (which might be relative to the current one)
837
* @return boolean true if the new frame is this code's window
840
if (target.indexOf("dom=") == 0) {
841
target = target.substr(4);
846
eval("t=" + currentFrameString + "." + target);
849
var autWindow = this.browserbot.getCurrentWindow();
851
if (t.window == autWindow) {
860
eval("currentFrame=" + currentFrameString);
861
if (target == "relative=up") {
862
if (currentFrame.window.parent == autWindow) {
867
if (target == "relative=top") {
868
if (currentFrame.window.top == autWindow) {
873
if (autWindow.name == target && currentFrame.window == autWindow.parent) {
879
Selenium.prototype.getWhetherThisWindowMatchWindowExpression = function(currentWindowString, target) {
881
* Determine whether currentWindowString plus target identify the window containing this running code.
883
* <p>This is useful in proxy injection mode, where this code runs in every
884
* browser frame and window, and sometimes the selenium server needs to identify
885
* the "current" window. In this case, when the test calls selectWindow, this
886
* routine is called for each window to figure out which one has been selected.
887
* The selected window will return true, while all others will return false.</p>
889
* @param currentWindowString starting window
890
* @param target new window (which might be relative to the current one, e.g., "_parent")
891
* @return boolean true if the new window is this code's window
893
if (window.opener!=null && window.opener[target]!=null && window.opener[target]==window) {
899
Selenium.prototype.doWaitForPopUp = function(windowID, timeout) {
901
* Waits for a popup window to appear and load up.
903
* @param windowID the JavaScript window ID of the window that will appear
904
* @param timeout a timeout in milliseconds, after which the action will return with an error
906
var popupLoadedPredicate = function () {
907
var targetWindow = selenium.browserbot.getWindowByName(windowID, true);
908
if (!targetWindow) return false;
909
if (!targetWindow.location) return false;
910
if ("about:blank" == targetWindow.location) return false;
911
if (browserVersion.isKonqueror) {
912
if ("/" == targetWindow.location.href) {
913
// apparently Konqueror uses this as the temporary location, instead of about:blank
917
if (browserVersion.isSafari) {
918
if(targetWindow.location.href == selenium.browserbot.buttonWindow.location.href) {
919
// Apparently Safari uses this as the temporary location, instead of about:blank
921
LOG.debug("DGF what a world!");
925
if (!targetWindow.document) return false;
926
if (!selenium.browserbot.getCurrentWindow().document.readyState) {
927
// This is Firefox, with no readyState extension
930
if ('complete' != targetWindow.document.readyState) return false;
934
return Selenium.decorateFunctionWithTimeout(popupLoadedPredicate, timeout);
937
Selenium.prototype.doWaitForPopUp.dontCheckAlertsAndConfirms = true;
939
Selenium.prototype.doChooseCancelOnNextConfirmation = function() {
941
* By default, Selenium's overridden window.confirm() function will
942
* return true, as if the user had manually clicked OK. After running
943
* this command, the next call to confirm() will return false, as if
944
* the user had clicked Cancel.
947
this.browserbot.cancelNextConfirmation();
951
Selenium.prototype.doAnswerOnNextPrompt = function(answer) {
953
* Instructs Selenium to return the specified answer string in response to
954
* the next JavaScript prompt [window.prompt()].
957
* @param answer the answer to give in response to the prompt pop-up
959
this.browserbot.setNextPromptResult(answer);
962
Selenium.prototype.doGoBack = function() {
964
* Simulates the user clicking the "back" button on their browser.
967
this.browserbot.goBack();
970
Selenium.prototype.doRefresh = function() {
972
* Simulates the user clicking the "Refresh" button on their browser.
975
this.browserbot.refresh();
978
Selenium.prototype.doClose = function() {
980
* Simulates the user clicking the "close" button in the titlebar of a popup
983
this.browserbot.close();
986
Selenium.prototype.ensureNoUnhandledPopups = function() {
987
if (this.browserbot.hasAlerts()) {
988
throw new SeleniumError("There was an unexpected Alert! [" + this.browserbot.getNextAlert() + "]");
990
if ( this.browserbot.hasConfirmations() ) {
991
throw new SeleniumError("There was an unexpected Confirmation! [" + this.browserbot.getNextConfirmation() + "]");
995
Selenium.prototype.isAlertPresent = function() {
997
* Has an alert occurred?
1000
* This function never throws an exception
1002
* @return boolean true if there is an alert
1004
return this.browserbot.hasAlerts();
1007
Selenium.prototype.isPromptPresent = function() {
1009
* Has a prompt occurred?
1012
* This function never throws an exception
1014
* @return boolean true if there is a pending prompt
1016
return this.browserbot.hasPrompts();
1019
Selenium.prototype.isConfirmationPresent = function() {
1021
* Has confirm() been called?
1024
* This function never throws an exception
1026
* @return boolean true if there is a pending confirmation
1028
return this.browserbot.hasConfirmations();
1030
Selenium.prototype.getAlert = function() {
1032
* Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.
1034
* <p>Getting an alert has the same effect as manually clicking OK. If an
1035
* alert is generated but you do not get/verify it, the next Selenium action
1038
* <p>NOTE: under Selenium, JavaScript alerts will NOT pop up a visible alert
1041
* <p>NOTE: Selenium does NOT support JavaScript alerts that are generated in a
1042
* page's onload() event handler. In this case a visible dialog WILL be
1043
* generated and Selenium will hang until someone manually clicks OK.</p>
1044
* @return string The message of the most recent JavaScript alert
1046
if (!this.browserbot.hasAlerts()) {
1047
Assert.fail("There were no alerts");
1049
return this.browserbot.getNextAlert();
1051
Selenium.prototype.getAlert.dontCheckAlertsAndConfirms = true;
1053
Selenium.prototype.getConfirmation = function() {
1055
* Retrieves the message of a JavaScript confirmation dialog generated during
1056
* the previous action.
1059
* By default, the confirm function will return true, having the same effect
1060
* as manually clicking OK. This can be changed by prior execution of the
1061
* chooseCancelOnNextConfirmation command. If an confirmation is generated
1062
* but you do not get/verify it, the next Selenium action will fail.
1066
* NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible
1071
* NOTE: Selenium does NOT support JavaScript confirmations that are
1072
* generated in a page's onload() event handler. In this case a visible
1073
* dialog WILL be generated and Selenium will hang until you manually click
1077
* @return string the message of the most recent JavaScript confirmation dialog
1079
if (!this.browserbot.hasConfirmations()) {
1080
Assert.fail("There were no confirmations");
1082
return this.browserbot.getNextConfirmation();
1084
Selenium.prototype.getConfirmation.dontCheckAlertsAndConfirms = true;
1086
Selenium.prototype.getPrompt = function() {
1088
* Retrieves the message of a JavaScript question prompt dialog generated during
1089
* the previous action.
1091
* <p>Successful handling of the prompt requires prior execution of the
1092
* answerOnNextPrompt command. If a prompt is generated but you
1093
* do not get/verify it, the next Selenium action will fail.</p>
1095
* <p>NOTE: under Selenium, JavaScript prompts will NOT pop up a visible
1098
* <p>NOTE: Selenium does NOT support JavaScript prompts that are generated in a
1099
* page's onload() event handler. In this case a visible dialog WILL be
1100
* generated and Selenium will hang until someone manually clicks OK.</p>
1101
* @return string the message of the most recent JavaScript question prompt
1103
if (! this.browserbot.hasPrompts()) {
1104
Assert.fail("There were no prompts");
1106
return this.browserbot.getNextPrompt();
1109
Selenium.prototype.getLocation = function() {
1110
/** Gets the absolute URL of the current page.
1112
* @return string the absolute URL of the current page
1114
return this.browserbot.getCurrentWindow().location;
1117
Selenium.prototype.getTitle = function() {
1118
/** Gets the title of the current page.
1120
* @return string the title of the current page
1122
return this.browserbot.getTitle();
1126
Selenium.prototype.getBodyText = function() {
1128
* Gets the entire text of the page.
1129
* @return string the entire text of the page
1131
return this.browserbot.bodyText();
1135
Selenium.prototype.getValue = function(locator) {
1137
* Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter).
1138
* For checkbox/radio elements, the value will be "on" or "off" depending on
1139
* whether the element is checked or not.
1141
* @param locator an <a href="#locators">element locator</a>
1142
* @return string the element value, or "on/off" for checkbox/radio elements
1144
var element = this.browserbot.findElement(locator)
1145
return getInputValue(element).trim();
1148
Selenium.prototype.getText = function(locator) {
1150
* Gets the text of an element. This works for any element that contains
1151
* text. This command uses either the textContent (Mozilla-like browsers) or
1152
* the innerText (IE-like browsers) of the element, which is the rendered
1153
* text shown to the user.
1155
* @param locator an <a href="#locators">element locator</a>
1156
* @return string the text of the element
1158
var element = this.browserbot.findElement(locator);
1159
return getText(element).trim();
1162
Selenium.prototype.doHighlight = function(locator) {
1164
* Briefly changes the backgroundColor of the specified element yellow. Useful for debugging.
1166
* @param locator an <a href="#locators">element locator</a>
1168
var element = this.browserbot.findElement(locator);
1169
this.browserbot.highlight(element, true);
1172
Selenium.prototype.getEval = function(script) {
1173
/** Gets the result of evaluating the specified JavaScript snippet. The snippet may
1174
* have multiple lines, but only the result of the last line will be returned.
1176
* <p>Note that, by default, the snippet will run in the context of the "selenium"
1177
* object itself, so <code>this</code> will refer to the Selenium object, and <code>window</code> will
1178
* refer to the top-level runner test window, not the window of your application.</p>
1180
* <p>If you need a reference to the window of your application, you can refer
1181
* to <code>this.browserbot.getCurrentWindow()</code> and if you need to use
1182
* a locator to refer to a single element in your application page, you can
1183
* use <code>this.browserbot.findElement("foo")</code> where "foo" is your locator.</p>
1185
* @param script the JavaScript snippet to run
1186
* @return string the results of evaluating the snippet
1189
var result = eval(script);
1190
// Selenium RC doesn't allow returning null
1191
if (null == result) return "null";
1194
throw new SeleniumError("Threw an exception: " + e.message);
1198
Selenium.prototype.isChecked = function(locator) {
1200
* Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button.
1201
* @param locator an <a href="#locators">element locator</a> pointing to a checkbox or radio button
1202
* @return boolean true if the checkbox is checked, false otherwise
1204
var element = this.browserbot.findElement(locator);
1205
if (element.checked == null) {
1206
throw new SeleniumError("Element " + locator + " is not a toggle-button.");
1208
return element.checked;
1211
Selenium.prototype.getTable = function(tableCellAddress) {
1213
* Gets the text from a cell of a table. The cellAddress syntax
1214
* tableLocator.row.column, where row and column start at 0.
1216
* @param tableCellAddress a cell address, e.g. "foo.1.4"
1217
* @return string the text from the specified cell
1219
// This regular expression matches "tableName.row.column"
1220
// For example, "mytable.3.4"
1221
pattern = /(.*)\.(\d+)\.(\d+)/;
1223
if(!pattern.test(tableCellAddress)) {
1224
throw new SeleniumError("Invalid target format. Correct format is tableName.rowNum.columnNum");
1227
pieces = tableCellAddress.match(pattern);
1229
tableName = pieces[1];
1233
var table = this.browserbot.findElement(tableName);
1234
if (row > table.rows.length) {
1235
Assert.fail("Cannot access row " + row + " - table has " + table.rows.length + " rows");
1237
else if (col > table.rows[row].cells.length) {
1238
Assert.fail("Cannot access column " + col + " - table row has " + table.rows[row].cells.length + " columns");
1241
actualContent = getText(table.rows[row].cells[col]);
1242
return actualContent.trim();
1247
Selenium.prototype.getSelectedLabels = function(selectLocator) {
1248
/** Gets all option labels (visible text) for selected options in the specified select or multi-select element.
1250
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1251
* @return string[] an array of all selected option labels in the specified select drop-down
1253
return this.findSelectedOptionProperties(selectLocator, "text").join(",");
1256
Selenium.prototype.getSelectedLabel = function(selectLocator) {
1257
/** Gets option label (visible text) for selected option in the specified select element.
1259
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1260
* @return string the selected option label in the specified select drop-down
1262
return this.findSelectedOptionProperty(selectLocator, "text");
1265
Selenium.prototype.getSelectedValues = function(selectLocator) {
1266
/** Gets all option values (value attributes) for selected options in the specified select or multi-select element.
1268
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1269
* @return string[] an array of all selected option values in the specified select drop-down
1271
return this.findSelectedOptionProperties(selectLocator, "value").join(",");
1274
Selenium.prototype.getSelectedValue = function(selectLocator) {
1275
/** Gets option value (value attribute) for selected option in the specified select element.
1277
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1278
* @return string the selected option value in the specified select drop-down
1280
return this.findSelectedOptionProperty(selectLocator, "value");
1283
Selenium.prototype.getSelectedIndexes = function(selectLocator) {
1284
/** Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element.
1286
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1287
* @return string[] an array of all selected option indexes in the specified select drop-down
1289
return this.findSelectedOptionProperties(selectLocator, "index").join(",");
1292
Selenium.prototype.getSelectedIndex = function(selectLocator) {
1293
/** Gets option index (option number, starting at 0) for selected option in the specified select element.
1295
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1296
* @return string the selected option index in the specified select drop-down
1298
return this.findSelectedOptionProperty(selectLocator, "index");
1301
Selenium.prototype.getSelectedIds = function(selectLocator) {
1302
/** Gets all option element IDs for selected options in the specified select or multi-select element.
1304
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1305
* @return string[] an array of all selected option IDs in the specified select drop-down
1307
return this.findSelectedOptionProperties(selectLocator, "id").join(",");
1310
Selenium.prototype.getSelectedId = function(selectLocator) {
1311
/** Gets option element ID for selected option in the specified select element.
1313
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1314
* @return string the selected option ID in the specified select drop-down
1316
return this.findSelectedOptionProperty(selectLocator, "id");
1319
Selenium.prototype.isSomethingSelected = function(selectLocator) {
1320
/** Determines whether some option in a drop-down menu is selected.
1322
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1323
* @return boolean true if some option has been selected, false otherwise
1325
var element = this.browserbot.findElement(selectLocator);
1326
if (!("options" in element)) {
1327
throw new SeleniumError("Specified element is not a Select (has no options)");
1330
var selectedOptions = [];
1332
for (var i = 0; i < element.options.length; i++) {
1333
if (element.options[i].selected)
1341
Selenium.prototype.findSelectedOptionProperties = function(locator, property) {
1342
var element = this.browserbot.findElement(locator);
1343
if (!("options" in element)) {
1344
throw new SeleniumError("Specified element is not a Select (has no options)");
1347
var selectedOptions = [];
1349
for (var i = 0; i < element.options.length; i++) {
1350
if (element.options[i].selected)
1352
var propVal = element.options[i][property];
1353
if (propVal.replace) {
1354
propVal.replace(/,/g, "\\,");
1356
selectedOptions.push(propVal);
1359
if (selectedOptions.length == 0) Assert.fail("No option selected");
1360
return selectedOptions;
1363
Selenium.prototype.findSelectedOptionProperty = function(locator, property) {
1364
var selectedOptions = this.findSelectedOptionProperties(locator, property);
1365
if (selectedOptions.length > 1) {
1366
Assert.fail("More than one selected option!");
1368
return selectedOptions[0];
1371
Selenium.prototype.getSelectOptions = function(selectLocator) {
1372
/** Gets all option labels in the specified select drop-down.
1374
* @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1375
* @return string[] an array of all option labels in the specified select drop-down
1377
var element = this.browserbot.findElement(selectLocator);
1379
var selectOptions = [];
1381
for (var i = 0; i < element.options.length; i++) {
1382
var option = element.options[i].text.replace(/,/g, "\\,");
1383
selectOptions.push(option);
1386
return selectOptions.join(",");
1390
Selenium.prototype.getAttribute = function(attributeLocator) {
1392
* Gets the value of an element attribute.
1394
* @param attributeLocator an element locator followed by an @ sign and then the name of the attribute, e.g. "foo@bar"
1395
* @return string the value of the specified attribute
1397
var result = this.browserbot.findAttribute(attributeLocator);
1398
if (result == null) {
1399
throw new SeleniumError("Could not find element attribute: " + attributeLocator);
1404
Selenium.prototype.isTextPresent = function(pattern) {
1406
* Verifies that the specified text pattern appears somewhere on the rendered page shown to the user.
1407
* @param pattern a <a href="#patterns">pattern</a> to match with the text of the page
1408
* @return boolean true if the pattern matches the text, false otherwise
1410
var allText = this.browserbot.bodyText();
1412
var patternMatcher = new PatternMatcher(pattern);
1413
if (patternMatcher.strategy == PatternMatcher.strategies.glob) {
1414
if (pattern.indexOf("glob:")==0) {
1415
pattern = pattern.substring("glob:".length); // strip off "glob:"
1417
patternMatcher.matcher = new PatternMatcher.strategies.globContains(pattern);
1419
else if (patternMatcher.strategy == PatternMatcher.strategies.exact) {
1420
pattern = pattern.substring("exact:".length); // strip off "exact:"
1421
return allText.indexOf(pattern) != -1;
1423
return patternMatcher.matches(allText);
1426
Selenium.prototype.isElementPresent = function(locator) {
1428
* Verifies that the specified element is somewhere on the page.
1429
* @param locator an <a href="#locators">element locator</a>
1430
* @return boolean true if the element is present, false otherwise
1433
this.browserbot.findElement(locator);
1440
Selenium.prototype.isVisible = function(locator) {
1442
* Determines if the specified element is visible. An
1443
* element can be rendered invisible by setting the CSS "visibility"
1444
* property to "hidden", or the "display" property to "none", either for the
1445
* element itself or one if its ancestors. This method will fail if
1446
* the element is not present.
1448
* @param locator an <a href="#locators">element locator</a>
1449
* @return boolean true if the specified element is visible, false otherwise
1452
element = this.browserbot.findElement(locator);
1453
var visibility = this.findEffectiveStyleProperty(element, "visibility");
1454
var _isDisplayed = this._isDisplayed(element);
1455
return (visibility != "hidden" && _isDisplayed);
1458
Selenium.prototype.findEffectiveStyleProperty = function(element, property) {
1459
var effectiveStyle = this.findEffectiveStyle(element);
1460
var propertyValue = effectiveStyle[property];
1461
if (propertyValue == 'inherit' && element.parentNode.style) {
1462
return this.findEffectiveStyleProperty(element.parentNode, property);
1464
return propertyValue;
1467
Selenium.prototype._isDisplayed = function(element) {
1468
var display = this.findEffectiveStyleProperty(element, "display");
1469
if (display == "none") return false;
1470
if (element.parentNode.style) {
1471
return this._isDisplayed(element.parentNode);
1476
Selenium.prototype.findEffectiveStyle = function(element) {
1477
if (element.style == undefined) {
1478
return undefined; // not a styled element
1480
var window = this.browserbot.getCurrentWindow();
1481
if (window.getComputedStyle) {
1483
return window.getComputedStyle(element, null);
1485
if (element.currentStyle) {
1486
// non-standard IE alternative
1487
return element.currentStyle;
1488
// TODO: this won't really work in a general sense, as
1489
// currentStyle is not identical to getComputedStyle()
1490
// ... but it's good enough for "visibility"
1492
throw new SeleniumError("cannot determine effective stylesheet in this browser");
1495
Selenium.prototype.isEditable = function(locator) {
1497
* Determines whether the specified input element is editable, ie hasn't been disabled.
1498
* This method will fail if the specified element isn't an input element.
1500
* @param locator an <a href="#locators">element locator</a>
1501
* @return boolean true if the input element is editable, false otherwise
1503
var element = this.browserbot.findElement(locator);
1504
if (element.value == undefined) {
1505
Assert.fail("Element " + locator + " is not an input.");
1507
return !element.disabled;
1510
Selenium.prototype.getAllButtons = function() {
1511
/** Returns the IDs of all buttons on the page.
1513
* <p>If a given button has no ID, it will appear as "" in this array.</p>
1515
* @return string[] the IDs of all buttons on the page
1517
return this.browserbot.getAllButtons();
1520
Selenium.prototype.getAllLinks = function() {
1521
/** Returns the IDs of all links on the page.
1523
* <p>If a given link has no ID, it will appear as "" in this array.</p>
1525
* @return string[] the IDs of all links on the page
1527
return this.browserbot.getAllLinks();
1530
Selenium.prototype.getAllFields = function() {
1531
/** Returns the IDs of all input fields on the page.
1533
* <p>If a given field has no ID, it will appear as "" in this array.</p>
1535
* @return string[] the IDs of all field on the page
1537
return this.browserbot.getAllFields();
1540
Selenium.prototype.getAttributeFromAllWindows = function(attributeName) {
1541
/** Returns every instance of some attribute from all known windows.
1543
* @param attributeName name of an attribute on the windows
1544
* @return string[] the set of values of this attribute from all known windows.
1546
var attributes = new Array();
1548
var win = selenium.browserbot.topWindow;
1550
// DGF normally you should use []s instead of eval "win."+attributeName
1551
// but in this case, attributeName may contain dots (e.g. document.title)
1552
// in that case, we have no choice but to use eval...
1553
attributes.push(eval("win."+attributeName));
1554
for (var windowName in this.browserbot.openedWindows)
1557
win = selenium.browserbot.openedWindows[windowName];
1558
attributes.push(eval("win."+attributeName));
1559
} catch (e) {} // DGF If we miss one... meh. It's probably closed or inaccessible anyway.
1564
Selenium.prototype.findWindow = function(soughtAfterWindowPropertyValue) {
1565
var targetPropertyName = "name";
1566
if (soughtAfterWindowPropertyValue.match("^title=")) {
1567
targetPropertyName = "document.title";
1568
soughtAfterWindowPropertyValue = soughtAfterWindowPropertyValue.replace(/^title=/, "");
1572
// If we are not in proxy injection mode, then the top-level test window will be named myiframe.
1573
// But as far as the interface goes, we are expected to match a blank string to this window, if
1574
// we are searching with respect to the widow name.
1575
// So make a special case so that this logic will work:
1576
if (PatternMatcher.matches(soughtAfterWindowPropertyValue, "")) {
1577
return this.browserbot.getCurrentWindow();
1581
// DGF normally you should use []s instead of eval "win."+attributeName
1582
// but in this case, attributeName may contain dots (e.g. document.title)
1583
// in that case, we have no choice but to use eval...
1584
if (PatternMatcher.matches(soughtAfterWindowPropertyValue, eval("this.browserbot.topWindow." + targetPropertyName))) {
1585
return this.browserbot.topWindow;
1587
for (windowName in selenium.browserbot.openedWindows) {
1588
var openedWindow = selenium.browserbot.openedWindows[windowName];
1589
if (PatternMatcher.matches(soughtAfterWindowPropertyValue, eval("openedWindow." + targetPropertyName))) {
1590
return openedWindow;
1593
throw new SeleniumError("could not find window with property " + targetPropertyName + " matching " + soughtAfterWindowPropertyValue);
1596
Selenium.prototype.doDragdrop = function(locator, movementsString) {
1597
/** deprecated - use dragAndDrop instead
1599
* @param locator an element locator
1600
* @param movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
1602
this.doDragAndDrop(locator, movementsString);
1605
Selenium.prototype.doSetMouseSpeed = function(pixels) {
1606
/** Configure the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
1607
* <p>Setting this value to 0 means that we'll send a "mousemove" event to every single pixel
1608
* in between the start location and the end location; that can be very slow, and may
1609
* cause some browsers to force the JavaScript to timeout.</p>
1611
* <p>If the mouse speed is greater than the distance between the two dragged objects, we'll
1612
* just send one "mousemove" at the start location and then one final one at the end location.</p>
1613
* @param pixels the number of pixels between "mousemove" events
1615
this.mouseSpeed = pixels;
1618
Selenium.prototype.getMouseSpeed = function() {
1619
/** Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
1621
* @return number the number of pixels between "mousemove" events during dragAndDrop commands (default=10)
1623
this.mouseSpeed = pixels;
1627
Selenium.prototype.doDragAndDrop = function(locator, movementsString) {
1628
/** Drags an element a certain distance and then drops it
1629
* @param locator an element locator
1630
* @param movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
1632
var element = this.browserbot.findElement(locator);
1633
var clientStartXY = getClientXY(element)
1634
var clientStartX = clientStartXY[0];
1635
var clientStartY = clientStartXY[1];
1637
var movements = movementsString.split(/,/);
1638
var movementX = Number(movements[0]);
1639
var movementY = Number(movements[1]);
1641
var clientFinishX = ((clientStartX + movementX) < 0) ? 0 : (clientStartX + movementX);
1642
var clientFinishY = ((clientStartY + movementY) < 0) ? 0 : (clientStartY + movementY);
1644
var mouseSpeed = this.mouseSpeed;
1645
var move = function(current, dest) {
1646
if (current == dest) return current;
1647
if (Math.abs(current - dest) < mouseSpeed) return dest;
1648
return (current < dest) ? current + mouseSpeed : current - mouseSpeed;
1651
this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientStartX, clientStartY);
1652
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientStartX, clientStartY);
1653
var clientX = clientStartX;
1654
var clientY = clientStartY;
1656
while ((clientX != clientFinishX) || (clientY != clientFinishY)) {
1657
clientX = move(clientX, clientFinishX);
1658
clientY = move(clientY, clientFinishY);
1659
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientX, clientY);
1662
this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientFinishX, clientFinishY);
1663
this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientFinishX, clientFinishY);
1666
Selenium.prototype.doDragAndDropToObject = function(locatorOfObjectToBeDragged, locatorOfDragDestinationObject) {
1667
/** Drags an element and drops it on another element
1669
* @param locatorOfObjectToBeDragged an element to be dragged
1670
* @param locatorOfDragDestinationObject an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped
1672
var startX = this.getElementPositionLeft(locatorOfObjectToBeDragged);
1673
var startY = this.getElementPositionTop(locatorOfObjectToBeDragged);
1675
var destinationLeftX = this.getElementPositionLeft(locatorOfDragDestinationObject);
1676
var destinationTopY = this.getElementPositionTop(locatorOfDragDestinationObject);
1677
var destinationWidth = this.getElementWidth(locatorOfDragDestinationObject);
1678
var destinationHeight = this.getElementHeight(locatorOfDragDestinationObject);
1680
var endX = Math.round(destinationLeftX + (destinationWidth / 2));
1681
var endY = Math.round(destinationTopY + (destinationHeight / 2));
1683
var deltaX = endX - startX;
1684
var deltaY = endY - startY;
1686
var movementsString = "" + deltaX + "," + deltaY;
1688
this.doDragAndDrop(locatorOfObjectToBeDragged, movementsString);
1691
Selenium.prototype.doWindowFocus = function(windowName) {
1692
/** Gives focus to a window
1694
* @param windowName name of the window to be given focus
1696
this.findWindow(windowName).focus();
1700
Selenium.prototype.doWindowMaximize = function(windowName) {
1701
/** Resize window to take up the entire screen
1703
* @param windowName name of the window to be enlarged
1705
var window = this.findWindow(windowName);
1706
if (window!=null && window.screen) {
1708
window.outerHeight = screen.availHeight;
1709
window.outerWidth = screen.availWidth;
1713
Selenium.prototype.getAllWindowIds = function() {
1714
/** Returns the IDs of all windows that the browser knows about.
1716
* @return string[] the IDs of all windows that the browser knows about.
1718
return this.getAttributeFromAllWindows("id");
1721
Selenium.prototype.getAllWindowNames = function() {
1722
/** Returns the names of all windows that the browser knows about.
1724
* @return string[] the names of all windows that the browser knows about.
1726
return this.getAttributeFromAllWindows("name");
1729
Selenium.prototype.getAllWindowTitles = function() {
1730
/** Returns the titles of all windows that the browser knows about.
1732
* @return string[] the titles of all windows that the browser knows about.
1734
return this.getAttributeFromAllWindows("document.title");
1737
Selenium.prototype.getHtmlSource = function() {
1738
/** Returns the entire HTML source between the opening and
1739
* closing "html" tags.
1741
* @return string the entire HTML source
1743
return this.browserbot.getDocument().getElementsByTagName("html")[0].innerHTML;
1746
Selenium.prototype.doSetCursorPosition = function(locator, position) {
1748
* Moves the text cursor to the specified position in the given input element or textarea.
1749
* This method will fail if the specified element isn't an input element or textarea.
1751
* @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
1752
* @param position the numerical position of the cursor in the field; position should be 0 to move the position to the beginning of the field. You can also set the cursor to -1 to move it to the end of the field.
1754
var element = this.browserbot.findElement(locator);
1755
if (element.value == undefined) {
1756
Assert.fail("Element " + locator + " is not an input.");
1758
if (position == -1) {
1759
position = element.value.length;
1762
if( element.setSelectionRange && !browserVersion.isOpera) {
1764
element.setSelectionRange(/*start*/position,/*end*/position);
1766
else if( element.createTextRange ) {
1767
triggerEvent(element, 'focus', false);
1768
var range = element.createTextRange();
1769
range.collapse(true);
1770
range.moveEnd('character',position);
1771
range.moveStart('character',position);
1776
Selenium.prototype.getElementIndex = function(locator) {
1778
* Get the relative index of an element to its parent (starting from 0). The comment node and empty text node
1781
* @param locator an <a href="#locators">element locator</a> pointing to an element
1782
* @return number of relative index of the element to its parent (starting from 0)
1784
var element = this.browserbot.findElement(locator);
1785
var previousSibling;
1787
while ((previousSibling = element.previousSibling) != null) {
1788
if (!this._isCommentOrEmptyTextNode(previousSibling)) {
1791
element = previousSibling;
1796
Selenium.prototype.isOrdered = function(locator1, locator2) {
1798
* Check if these two elements have same parent and are ordered. Two same elements will
1799
* not be considered ordered.
1801
* @param locator1 an <a href="#locators">element locator</a> pointing to the first element
1802
* @param locator2 an <a href="#locators">element locator</a> pointing to the second element
1803
* @return boolean true if two elements are ordered and have same parent, false otherwise
1805
var element1 = this.browserbot.findElement(locator1);
1806
var element2 = this.browserbot.findElement(locator2);
1807
if (element1 === element2) return false;
1809
var previousSibling;
1810
while ((previousSibling = element2.previousSibling) != null) {
1811
if (previousSibling === element1) {
1814
element2 = previousSibling;
1819
Selenium.prototype._isCommentOrEmptyTextNode = function(node) {
1820
return node.nodeType == 8 || ((node.nodeType == 3) && !(/[^\t\n\r ]/.test(node.data)));
1823
Selenium.prototype.getElementPositionLeft = function(locator) {
1825
* Retrieves the horizontal position of an element
1827
* @param locator an <a href="#locators">element locator</a> pointing to an element OR an element itself
1828
* @return number of pixels from the edge of the frame.
1831
if ("string"==typeof locator) {
1832
element = this.browserbot.findElement(locator);
1837
var x = element.offsetLeft;
1838
var elementParent = element.offsetParent;
1840
while (elementParent != null)
1844
if( (elementParent.tagName != "TABLE") && (elementParent.tagName != "BODY") )
1846
x += elementParent.clientLeft;
1849
else // Netscape/DOM
1851
if(elementParent.tagName == "TABLE")
1853
var parentBorder = parseInt(elementParent.border);
1854
if(isNaN(parentBorder))
1856
var parentFrame = elementParent.getAttribute('frame');
1857
if(parentFrame != null)
1862
else if(parentBorder > 0)
1868
x += elementParent.offsetLeft;
1869
elementParent = elementParent.offsetParent;
1874
Selenium.prototype.getElementPositionTop = function(locator) {
1876
* Retrieves the vertical position of an element
1878
* @param locator an <a href="#locators">element locator</a> pointing to an element OR an element itself
1879
* @return number of pixels from the edge of the frame.
1882
if ("string"==typeof locator) {
1883
element = this.browserbot.findElement(locator);
1891
while (element != null)
1895
if( (element.tagName != "TABLE") && (element.tagName != "BODY") )
1897
y += element.clientTop;
1900
else // Netscape/DOM
1902
if(element.tagName == "TABLE")
1904
var parentBorder = parseInt(element.border);
1905
if(isNaN(parentBorder))
1907
var parentFrame = element.getAttribute('frame');
1908
if(parentFrame != null)
1913
else if(parentBorder > 0)
1919
y += element.offsetTop;
1921
// Netscape can get confused in some cases, such that the height of the parent is smaller
1922
// than that of the element (which it shouldn't really be). If this is the case, we need to
1923
// exclude this element, since it will result in too large a 'top' return value.
1924
if (element.offsetParent && element.offsetParent.offsetHeight && element.offsetParent.offsetHeight < element.offsetHeight)
1926
// skip the parent that's too small
1927
element = element.offsetParent.offsetParent;
1932
element = element.offsetParent;
1938
Selenium.prototype.getElementWidth = function(locator) {
1940
* Retrieves the width of an element
1942
* @param locator an <a href="#locators">element locator</a> pointing to an element
1943
* @return number width of an element in pixels
1945
var element = this.browserbot.findElement(locator);
1946
return element.offsetWidth;
1949
Selenium.prototype.getElementHeight = function(locator) {
1951
* Retrieves the height of an element
1953
* @param locator an <a href="#locators">element locator</a> pointing to an element
1954
* @return number height of an element in pixels
1956
var element = this.browserbot.findElement(locator);
1957
return element.offsetHeight;
1960
Selenium.prototype.getCursorPosition = function(locator) {
1962
* Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers.
1964
* <p>Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to
1965
* return the position of the last location of the cursor, even though the cursor is now gone from the page. This is filed as <a href="http://jira.openqa.org/browse/SEL-243">SEL-243</a>.</p>
1966
* This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element.
1968
* @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
1969
* @return number the numerical position of the cursor in the field
1971
var element = this.browserbot.findElement(locator);
1972
var doc = this.browserbot.getDocument();
1973
var win = this.browserbot.getCurrentWindow();
1974
if( doc.selection && !browserVersion.isOpera){
1976
var selectRange = doc.selection.createRange().duplicate();
1977
var elementRange = element.createTextRange();
1978
selectRange.move("character",0);
1979
elementRange.move("character",0);
1980
var inRange1 = selectRange.inRange(elementRange);
1981
var inRange2 = elementRange.inRange(selectRange);
1982
elementRange.setEndPoint("EndToEnd", selectRange);
1984
Assert.fail("There is no cursor on this page!");
1986
var answer = String(elementRange.text).replace(/\r/g,"").length;
1989
if (typeof(element.selectionStart) != "undefined") {
1990
if (win.getSelection && typeof(win.getSelection().rangeCount) != undefined && win.getSelection().rangeCount == 0) {
1991
Assert.fail("There is no cursor on this page!");
1993
return element.selectionStart;
1996
throw new Error("Couldn't detect cursor position on this browser!");
2000
Selenium.prototype.doSetContext = function(context, logLevelThreshold) {
2002
* Writes a message to the status bar and adds a note to the browser-side
2005
* <p>If logLevelThreshold is specified, set the threshold for logging
2006
* to that level (debug, info, warn, error).</p>
2008
* <p>(Note that the browser-side logs will <i>not</i> be sent back to the
2009
* server, and are invisible to the Client Driver.)</p>
2012
* the message to be sent to the browser
2013
* @param logLevelThreshold one of "debug", "info", "warn", "error", sets the threshold for browser-side logging
2015
if (logLevelThreshold==null || logLevelThreshold=="") {
2016
return this.browserbot.setContext(context);
2018
return this.browserbot.setContext(context, logLevelThreshold);
2021
Selenium.prototype.getExpression = function(expression) {
2023
* Returns the specified expression.
2025
* <p>This is useful because of JavaScript preprocessing.
2026
* It is used to generate commands like assertExpression and waitForExpression.</p>
2028
* @param expression the value to return
2029
* @return string the value passed in
2034
Selenium.prototype.doWaitForCondition = function(script, timeout) {
2036
* Runs the specified JavaScript snippet repeatedly until it evaluates to "true".
2037
* The snippet may have multiple lines, but only the result of the last line
2038
* will be considered.
2040
* <p>Note that, by default, the snippet will be run in the runner's test window, not in the window
2041
* of your application. To get the window of your application, you can use
2042
* the JavaScript snippet <code>selenium.browserbot.getCurrentWindow()</code>, and then
2043
* run your JavaScript in there</p>
2044
* @param script the JavaScript snippet to run
2045
* @param timeout a timeout in milliseconds, after which this command will return with an error
2047
return Selenium.decorateFunctionWithTimeout(function () {
2048
return eval(script);
2052
Selenium.prototype.doWaitForCondition.dontCheckAlertsAndConfirms = true;
2054
Selenium.prototype.doSetTimeout = function(timeout) {
2056
* Specifies the amount of time that Selenium will wait for actions to complete.
2058
* <p>Actions that require waiting include "open" and the "waitFor*" actions.</p>
2059
* The default timeout is 30 seconds.
2060
* @param timeout a timeout in milliseconds, after which the action will return with an error
2063
timeout = Selenium.DEFAULT_TIMEOUT;
2065
this.defaultTimeout = timeout;
2068
Selenium.prototype.doWaitForPageToLoad = function(timeout) {
2070
* Waits for a new page to load.
2072
* <p>You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc.
2073
* (which are only available in the JS API).</p>
2075
* <p>Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded"
2076
* flag when it first notices a page load. Running any other Selenium command after
2077
* turns the flag to false. Hence, if you want to wait for a page to load, you must
2078
* wait immediately after a Selenium command that caused a page-load.</p>
2079
* @param timeout a timeout in milliseconds, after which this command will return with an error
2081
// in pi-mode, the test and the harness share the window; thus if we are executing this code, then we have loaded
2082
if (window["proxyInjectionMode"] == null || !window["proxyInjectionMode"]) {
2083
return this.makePageLoadCondition(timeout);
2087
Selenium.prototype._isNewPageLoaded = function() {
2088
return this.browserbot.isNewPageLoaded();
2091
Selenium.prototype.doWaitForPageToLoad.dontCheckAlertsAndConfirms = true;
2094
* Evaluate a parameter, performing JavaScript evaluation and variable substitution.
2095
* If the string matches the pattern "javascript{ ... }", evaluate the string between the braces.
2097
Selenium.prototype.preprocessParameter = function(value) {
2098
var match = value.match(/^javascript\{((.|\r?\n)+)\}$/);
2099
if (match && match[1]) {
2100
return eval(match[1]).toString();
2102
return this.replaceVariables(value);
2106
* Search through str and replace all variable references ${varName} with their
2107
* value in storedVars.
2109
Selenium.prototype.replaceVariables = function(str) {
2110
var stringResult = str;
2112
// Find all of the matching variable references
2113
var match = stringResult.match(/\$\{\w+\}/g);
2115
return stringResult;
2118
// For each match, lookup the variable value, and replace if found
2119
for (var i = 0; match && i < match.length; i++) {
2120
var variable = match[i]; // The replacement variable, with ${}
2121
var name = variable.substring(2, variable.length - 1); // The replacement variable without ${}
2122
var replacement = storedVars[name];
2123
if (replacement != undefined) {
2124
stringResult = stringResult.replace(variable, replacement);
2127
return stringResult;
2130
Selenium.prototype.getCookie = function() {
2132
* Return all cookies of the current page under test.
2134
* @return string all cookies of the current page under test
2136
var doc = this.browserbot.getDocument();
2140
Selenium.prototype.doCreateCookie = function(nameValuePair, optionsString) {
2142
* Create a new cookie whose path and domain are same with those of current page
2143
* under test, unless you specified a path for this cookie explicitly.
2145
* @param nameValuePair name and value of the cookie in a format "name=value"
2146
* @param optionsString options for the cookie. Currently supported options include 'path' and 'max_age'.
2147
* the optionsString's format is "path=/path/, max_age=60". The order of options are irrelevant, the unit
2148
* of the value of 'max_age' is second.
2150
var results = /[^\s=\[\]\(\),"\/\?@:;]+=[^\s=\[\]\(\),"\/\?@:;]*/.test(nameValuePair);
2152
throw new SeleniumError("Invalid parameter.");
2154
var cookie = nameValuePair.trim();
2155
results = /max_age=(\d+)/.exec(optionsString);
2157
var expireDateInMilliseconds = (new Date()).getTime() + results[1] * 1000;
2158
cookie += "; expires=" + new Date(expireDateInMilliseconds).toGMTString();
2160
results = /path=([^\s,]+)[,]?/.exec(optionsString);
2162
var path = results[1];
2163
if (browserVersion.khtml) {
2164
// Safari and conquerer don't like paths with / at the end
2166
path = path.replace(/\/$/, "");
2169
cookie += "; path=" + path;
2171
LOG.debug("Setting cookie to: " + cookie);
2172
this.browserbot.getDocument().cookie = cookie;
2175
Selenium.prototype.doDeleteCookie = function(name,path) {
2177
* Delete a named cookie with specified path.
2179
* @param name the name of the cookie to be deleted
2180
* @param path the path property of the cookie to be deleted
2182
// set the expire time of the cookie to be deleted to one minute before now.
2184
if (browserVersion.khtml) {
2185
// Safari and conquerer don't like paths with / at the end
2187
path = path.replace(/\/$/, "");
2190
var expireDateInMilliseconds = (new Date()).getTime() + (-1 * 1000);
2191
var cookie = name.trim() + "=deleted; path=" + path + "; expires=" + new Date(expireDateInMilliseconds).toGMTString();
2192
LOG.debug("Setting cookie to: " + cookie);
2193
this.browserbot.getDocument().cookie = cookie;
2198
* Factory for creating "Option Locators".
2199
* An OptionLocator is an object for dealing with Select options (e.g. for
2200
* finding a specified option, or asserting that the selected option of
2201
* Select element matches some condition.
2202
* The type of locator returned by the factory depends on the locator string:
2203
* label=<exp> (OptionLocatorByLabel)
2204
* value=<exp> (OptionLocatorByValue)
2205
* index=<exp> (OptionLocatorByIndex)
2206
* id=<exp> (OptionLocatorById)
2207
* <exp> (default is OptionLocatorByLabel).
2209
function OptionLocatorFactory() {
2212
OptionLocatorFactory.prototype.fromLocatorString = function(locatorString) {
2213
var locatorType = 'label';
2214
var locatorValue = locatorString;
2215
// If there is a locator prefix, use the specified strategy
2216
var result = locatorString.match(/^([a-zA-Z]+)=(.*)/);
2218
locatorType = result[1];
2219
locatorValue = result[2];
2221
if (this.optionLocators == undefined) {
2222
this.registerOptionLocators();
2224
if (this.optionLocators[locatorType]) {
2225
return new this.optionLocators[locatorType](locatorValue);
2227
throw new SeleniumError("Unkown option locator type: " + locatorType);
2231
* To allow for easy extension, all of the option locators are found by
2232
* searching for all methods of OptionLocatorFactory.prototype that start
2233
* with "OptionLocatorBy".
2234
* TODO: Consider using the term "Option Specifier" instead of "Option Locator".
2236
OptionLocatorFactory.prototype.registerOptionLocators = function() {
2237
this.optionLocators={};
2238
for (var functionName in this) {
2239
var result = /OptionLocatorBy([A-Z].+)$/.exec(functionName);
2240
if (result != null) {
2241
var locatorName = result[1].lcfirst();
2242
this.optionLocators[locatorName] = this[functionName];
2248
* OptionLocator for options identified by their labels.
2250
OptionLocatorFactory.prototype.OptionLocatorByLabel = function(label) {
2252
this.labelMatcher = new PatternMatcher(this.label);
2253
this.findOption = function(element) {
2254
for (var i = 0; i < element.options.length; i++) {
2255
if (this.labelMatcher.matches(element.options[i].text)) {
2256
return element.options[i];
2259
throw new SeleniumError("Option with label '" + this.label + "' not found");
2262
this.assertSelected = function(element) {
2263
var selectedLabel = element.options[element.selectedIndex].text;
2264
Assert.matches(this.label, selectedLabel)
2269
* OptionLocator for options identified by their values.
2271
OptionLocatorFactory.prototype.OptionLocatorByValue = function(value) {
2273
this.valueMatcher = new PatternMatcher(this.value);
2274
this.findOption = function(element) {
2275
for (var i = 0; i < element.options.length; i++) {
2276
if (this.valueMatcher.matches(element.options[i].value)) {
2277
return element.options[i];
2280
throw new SeleniumError("Option with value '" + this.value + "' not found");
2283
this.assertSelected = function(element) {
2284
var selectedValue = element.options[element.selectedIndex].value;
2285
Assert.matches(this.value, selectedValue)
2290
* OptionLocator for options identified by their index.
2292
OptionLocatorFactory.prototype.OptionLocatorByIndex = function(index) {
2293
this.index = Number(index);
2294
if (isNaN(this.index) || this.index < 0) {
2295
throw new SeleniumError("Illegal Index: " + index);
2298
this.findOption = function(element) {
2299
if (element.options.length <= this.index) {
2300
throw new SeleniumError("Index out of range. Only " + element.options.length + " options available");
2302
return element.options[this.index];
2305
this.assertSelected = function(element) {
2306
Assert.equals(this.index, element.selectedIndex);
2311
* OptionLocator for options identified by their id.
2313
OptionLocatorFactory.prototype.OptionLocatorById = function(id) {
2315
this.idMatcher = new PatternMatcher(this.id);
2316
this.findOption = function(element) {
2317
for (var i = 0; i < element.options.length; i++) {
2318
if (this.idMatcher.matches(element.options[i].id)) {
2319
return element.options[i];
2322
throw new SeleniumError("Option with id '" + this.id + "' not found");
2325
this.assertSelected = function(element) {
2326
var selectedId = element.options[element.selectedIndex].id;
2327
Assert.matches(this.id, selectedId)