Project

General

Profile

1 4307 leinfelder
/*
2
 * Copyright 2004 ThoughtWorks, Inc
3
 *
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
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
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.
15
 *
16
 */
17
18
// TODO: stop navigating this.browserbot.document() ... it breaks encapsulation
19
20
var storedVars = new Object();
21
22
function Selenium(browserbot) {
23
    /**
24
     * Defines an object that runs Selenium commands.
25
     *
26
     * <h3><a name="locators"></a>Element Locators</h3>
27
     * <p>
28
     * Element Locators tell Selenium which HTML element a command refers to.
29
     * The format of a locator is:</p>
30
     * <blockquote>
31
     * <em>locatorType</em><strong>=</strong><em>argument</em>
32
     * </blockquote>
33
     *
34
     * <p>
35
     * We support the following strategies for locating elements:
36
     * </p>
37
     *
38
     * <ul>
39
     * <li><strong>identifier</strong>=<em>id</em>:
40
     * Select the element with the specified &#64;id attribute. If no match is
41
     * found, select the first element whose &#64;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 &#64;id attribute.</li>
45
     *
46
     * <li><strong>name</strong>=<em>name</em>:
47
     * Select the first element with the specified &#64;name attribute.
48
     * <ul class="first last simple">
49
     * <li>username</li>
50
     * <li>name=username</li>
51
     * </ul>
52
     *
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>
54
     *
55
     * <ul class="first last simple">
56
     * <li>name=flavour value=chocolate</li>
57
     * </ul>
58
     * </li>
59
     * <li><strong>dom</strong>=<em>javascriptExpression</em>:
60
     *
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>
67
     * </ul>
68
     *
69
     * </li>
70
     *
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[&#64;alt='The image alt text']</li>
75
     * <li>xpath=//table[&#64;id='table1']//tr[4]/td[2]</li>
76
     * <li>xpath=//a[contains(&#64;href,'#id1')]</li>
77
     * <li>xpath=//a[contains(&#64;href,'#id1')]/&#64;class</li>
78
     * <li>xpath=(//table[&#64;class='stylee'])//th[text()='theHeaderText']/../td</li>
79
     * <li>xpath=//input[&#64;name='name2' and &#64;value='yes']</li>
80
     * <li>xpath=//*[text()="right"]</li>
81
     *
82
     * </ul>
83
     * </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>
89
     * </ul>
90
     *
91
     * </li>
92
     *
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>
98
     * </ul>
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>
100
     * </li>
101
     * </ul>
102
     *
103
     * <p>
104
     * Without an explicit locator prefix, Selenium uses the following default
105
     * strategies:
106
     * </p>
107
     *
108
     * <ul class="simple">
109
     * <li><strong>dom</strong>, for locators starting with &quot;document.&quot;</li>
110
     * <li><strong>xpath</strong>, for locators starting with &quot;//&quot;</li>
111
     * <li><strong>identifier</strong>, otherwise</li>
112
     * </ul>
113
     *
114
     * <h3><a name="element-filters">Element Filters</a></h3>
115
     * <blockquote>
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>
118
     * <blockquote>
119
     * <em>filterType</em><strong>=</strong><em>argument</em></blockquote>
120
     *
121
     * <p>Supported element-filters are:</p>
122
     * <p><strong>value=</strong><em>valuePattern</em></p>
123
     * <blockquote>
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>
126
     * <blockquote>
127
     * Selects a single element based on its position in the list (offset from zero).</blockquote>
128
     * </blockquote>
129
     *
130
     * <h3><a name="patterns"></a>String-match Patterns</h3>
131
     *
132
     * <p>
133
     * Various Pattern syntaxes are available for matching string values:
134
     * </p>
135
     * <ul>
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
141
     * string.</li>
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>:
146
     *
147
     * Match a string exactly, verbatim, without any of that fancy wildcard
148
     * stuff.</li>
149
     * </ul>
150
     * <p>
151
     * If no pattern prefix is specified, Selenium assumes that it's a "glob"
152
     * pattern.
153
     * </p>
154
     */
155
    this.browserbot = browserbot;
156
    this.optionLocatorFactory = new OptionLocatorFactory();
157
    // DGF for backwards compatibility
158
    this.page = function() {
159
        return browserbot;
160
    };
161
    this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
162
    this.mouseSpeed = 10;
163
}
164
165
Selenium.DEFAULT_TIMEOUT = 30 * 1000;
166
Selenium.DEFAULT_MOUSE_SPEED = 10;
167
168
Selenium.decorateFunctionWithTimeout = function(f, timeout) {
169
    if (f == null) {
170
        return null;
171
    }
172
    var timeoutValue = parseInt(timeout);
173
    if (isNaN(timeoutValue)) {
174
        throw new SeleniumError("Timeout is not a number: '" + timeout + "'");
175
    }
176
    var now = new Date().getTime();
177
    var timeoutTime = now + timeoutValue;
178
    return function() {
179
        if (new Date().getTime() > timeoutTime) {
180
            throw new SeleniumError("Timed out after " + timeoutValue + "ms");
181
        }
182
        return f();
183
    };
184
}
185
186
Selenium.createForWindow = function(window, proxyInjectionMode) {
187
    if (!window.location) {
188
        throw "error: not a window!";
189
    }
190
    return new Selenium(BrowserBot.createForWindow(window, proxyInjectionMode));
191
};
192
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();
198
};
199
200
Selenium.prototype.doClick = function(locator) {
201
    /**
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
204
   * waitForPageToLoad.
205
   *
206
   * @param locator an element locator
207
   *
208
   */
209
   var element = this.browserbot.findElement(locator);
210
   this.browserbot.clickElement(element);
211
};
212
213
Selenium.prototype.doDoubleClick = function(locator) {
214
    /**
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
217
   * waitForPageToLoad.
218
   *
219
   * @param locator an element locator
220
   *
221
   */
222
   var element = this.browserbot.findElement(locator);
223
   this.browserbot.doubleClickElement(element);
224
};
225
226
Selenium.prototype.doClickAt = function(locator, coordString) {
227
    /**
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
230
   * waitForPageToLoad.
231
   *
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.
235
   *
236
   */
237
    var element = this.browserbot.findElement(locator);
238
    var clientXY = getClientXY(element, coordString)
239
    this.browserbot.clickElement(element, clientXY[0], clientXY[1]);
240
};
241
242
Selenium.prototype.doDoubleClickAt = function(locator, coordString) {
243
    /**
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
246
   * waitForPageToLoad.
247
   *
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.
251
   *
252
   */
253
    var element = this.browserbot.findElement(locator);
254
    var clientXY = getClientXY(element, coordString)
255
    this.browserbot.doubleClickElement(element, clientXY[0], clientXY[1]);
256
};
257
258
Selenium.prototype.doFireEvent = function(locator, eventName) {
259
    /**
260
   * Explicitly simulate an event, to trigger the corresponding &quot;on<em>event</em>&quot;
261
   * handler.
262
   *
263
   * @param locator an <a href="#locators">element locator</a>
264
   * @param eventName the event name, e.g. "focus" or "blur"
265
   */
266
    var element = this.browserbot.findElement(locator);
267
    triggerEvent(element, eventName, false);
268
};
269
270
Selenium.prototype.doKeyPress = function(locator, keySequence) {
271
    /**
272
   * Simulates a user pressing and releasing a key.
273
   *
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".
278
   */
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);
285
};
286
287
Selenium.prototype.doShiftKeyDown = function() {
288
    /**
289
   * Press the shift key and hold it down until doShiftUp() is called or a new page is loaded.
290
   *
291
   */
292
   this.browserbot.shiftKeyDown = true;
293
};
294
295
Selenium.prototype.doShiftKeyUp = function() {
296
    /**
297
   * Release the shift key.
298
   *
299
   */
300
   this.browserbot.shiftKeyDown = false;
301
};
302
303
Selenium.prototype.doMetaKeyDown = function() {
304
    /**
305
   * Press the meta key and hold it down until doMetaUp() is called or a new page is loaded.
306
   *
307
   */
308
   this.browserbot.metaKeyDown = true;
309
};
310
311
Selenium.prototype.doMetaKeyUp = function() {
312
    /**
313
   * Release the meta key.
314
   *
315
   */
316
   this.browserbot.metaKeyDown = false;
317
};
318
319
Selenium.prototype.doAltKeyDown = function() {
320
    /**
321
   * Press the alt key and hold it down until doAltUp() is called or a new page is loaded.
322
   *
323
   */
324
   this.browserbot.altKeyDown = true;
325
};
326
327
Selenium.prototype.doAltKeyUp = function() {
328
    /**
329
   * Release the alt key.
330
   *
331
   */
332
   this.browserbot.altKeyDown = false;
333
};
334
335
Selenium.prototype.doControlKeyDown = function() {
336
    /**
337
   * Press the control key and hold it down until doControlUp() is called or a new page is loaded.
338
   *
339
   */
340
   this.browserbot.controlKeyDown = true;
341
};
342
343
Selenium.prototype.doControlKeyUp = function() {
344
    /**
345
   * Release the control key.
346
   *
347
   */
348
   this.browserbot.controlKeyDown = false;
349
};
350
351
Selenium.prototype.doKeyDown = function(locator, keySequence) {
352
    /**
353
   * Simulates a user pressing a key (without releasing it yet).
354
   *
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".
359
   */
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);
366
};
367
368
Selenium.prototype.doKeyUp = function(locator, keySequence) {
369
    /**
370
   * Simulates a user releasing a key.
371
   *
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".
376
   */
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);
383
};
384
385
function getClientXY(element, coordString) {
386
   // Parse coordString
387
   var coords = null;
388
   var x;
389
   var y;
390
   if (coordString) {
391
      coords = coordString.split(/,/);
392
      x = Number(coords[0]);
393
      y = Number(coords[1]);
394
   }
395
   else {
396
      x = y = 0;
397
   }
398
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];
402
}
403
404
Selenium.prototype.doMouseOver = function(locator) {
405
    /**
406
   * Simulates a user hovering a mouse over the specified element.
407
   *
408
   * @param locator an <a href="#locators">element locator</a>
409
   */
410
    var element = this.browserbot.findElement(locator);
411
    this.browserbot.triggerMouseEvent(element, 'mouseover', true);
412
};
413
414
Selenium.prototype.doMouseOut = function(locator) {
415
   /**
416
   * Simulates a user moving the mouse pointer away from the specified element.
417
   *
418
   * @param locator an <a href="#locators">element locator</a>
419
   */
420
    var element = this.browserbot.findElement(locator);
421
    this.browserbot.triggerMouseEvent(element, 'mouseout', true);
422
};
423
424
Selenium.prototype.doMouseDown = function(locator) {
425
    /**
426
   * Simulates a user pressing the mouse button (without releasing it yet) on
427
   * the specified element.
428
   *
429
   * @param locator an <a href="#locators">element locator</a>
430
   */
431
   var element = this.browserbot.findElement(locator);
432
   this.browserbot.triggerMouseEvent(element, 'mousedown', true);
433
};
434
435
Selenium.prototype.doMouseDownAt = function(locator, coordString) {
436
    /**
437
   * Simulates a user pressing the mouse button (without releasing it yet) on
438
   * the specified element.
439
   *
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.
443
   */
444
    var element = this.browserbot.findElement(locator);
445
    var clientXY = getClientXY(element, coordString)
446
447
    this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientXY[0], clientXY[1]);
448
};
449
450
Selenium.prototype.doMouseUp = function(locator) {
451
    /**
452
   * Simulates a user pressing the mouse button (without releasing it yet) on
453
   * the specified element.
454
   *
455
   * @param locator an <a href="#locators">element locator</a>
456
   */
457
   var element = this.browserbot.findElement(locator);
458
   this.browserbot.triggerMouseEvent(element, 'mouseup', true);
459
};
460
461
Selenium.prototype.doMouseUpAt = function(locator, coordString) {
462
    /**
463
   * Simulates a user pressing the mouse button (without releasing it yet) on
464
   * the specified element.
465
   *
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.
469
   */
470
    var element = this.browserbot.findElement(locator);
471
    var clientXY = getClientXY(element, coordString)
472
473
    this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientXY[0], clientXY[1]);
474
};
475
476
Selenium.prototype.doMouseMove = function(locator) {
477
    /**
478
   * Simulates a user pressing the mouse button (without releasing it yet) on
479
   * the specified element.
480
   *
481
   * @param locator an <a href="#locators">element locator</a>
482
   */
483
   var element = this.browserbot.findElement(locator);
484
   this.browserbot.triggerMouseEvent(element, 'mousemove', true);
485
};
486
487
Selenium.prototype.doMouseMoveAt = function(locator, coordString) {
488
    /**
489
   * Simulates a user pressing the mouse button (without releasing it yet) on
490
   * the specified element.
491
   *
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.
495
   */
496
497
    var element = this.browserbot.findElement(locator);
498
    var clientXY = getClientXY(element, coordString)
499
500
    this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientXY[0], clientXY[1]);
501
};
502
503
Selenium.prototype.doType = function(locator, value) {
504
    /**
505
   * Sets the value of an input field, as though you typed it in.
506
   *
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>
509
   *
510
   * @param locator an <a href="#locators">element locator</a>
511
   * @param value the value to type
512
   */
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()");
515
    }
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();
520
    }
521
    this.browserbot.replaceText(element, value);
522
};
523
524
Selenium.prototype.doTypeKeys = function(locator, value) {
525
    /**
526
    * Simulates keystroke events on the specified element, as though you typed the value key-by-key.
527
    *
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>
530
    *
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
534
    * the field.</p>
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>
537
    *
538
    * @param locator an <a href="#locators">element locator</a>
539
    * @param value the value to type
540
    */
541
    var keys = new String(value).split("");
542
    for (var i = 0; i < keys.length; i++) {
543
        var c = keys[i];
544
        this.doKeyDown(locator, c);
545
        this.doKeyUp(locator, c);
546
        this.doKeyPress(locator, c);
547
    }
548
};
549
550
Selenium.prototype.doSetSpeed = function(value) {
551
 /**
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.
554
   *
555
   * @param value the number of milliseconds to pause after operation
556
   */
557
   throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
558
};
559
560
Selenium.prototype.doGetSpeed = function() {
561
 /**
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.
564
   *
565
   * See also setSpeed.
566
   */
567
   throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
568
};
569
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.");
574
    }
575
    return element;
576
}
577
578
Selenium.prototype.doCheck = function(locator) {
579
    /**
580
   * Check a toggle-button (checkbox/radio)
581
   *
582
   * @param locator an <a href="#locators">element locator</a>
583
   */
584
    this.findToggleButton(locator).checked = true;
585
};
586
587
Selenium.prototype.doUncheck = function(locator) {
588
    /**
589
   * Uncheck a toggle-button (checkbox/radio)
590
   *
591
   * @param locator an <a href="#locators">element locator</a>
592
   */
593
    this.findToggleButton(locator).checked = false;
594
};
595
596
Selenium.prototype.doSelect = function(selectLocator, optionLocator) {
597
    /**
598
   * Select an option from a drop-down using an option locator.
599
   *
600
   * <p>
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.
605
   * </p>
606
   * <ul>
607
   * <li><strong>label</strong>=<em>labelPattern</em>:
608
   * matches options based on their labels, i.e. the visible text. (This
609
   * is the default.)
610
   * <ul class="first last simple">
611
   * <li>label=regexp:^[Oo]ther</li>
612
   * </ul>
613
   * </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>
618
   * </ul>
619
   *
620
   *
621
   * </li>
622
   * <li><strong>id</strong>=<em>id</em>:
623
   *
624
   * matches options based on their ids.
625
   * <ul class="first last simple">
626
   * <li>id=option1</li>
627
   * </ul>
628
   * </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">
632
   *
633
   * <li>index=2</li>
634
   * </ul>
635
   * </li>
636
   * </ul>
637
   * <p>
638
   * If no option locator prefix is provided, the default behaviour is to match on <strong>label</strong>.
639
   * </p>
640
   *
641
   *
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)
644
   */
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)");
648
    }
649
    var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
650
    var option = locator.findOption(element);
651
    this.browserbot.selectOption(element, option);
652
};
653
654
655
656
Selenium.prototype.doAddSelection = function(locator, optionLocator) {
657
    /**
658
   * Add a selection to the set of selected options in a multi-select element using an option locator.
659
   *
660
   * @see #doSelect for details of option locators
661
   *
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)
664
   */
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)");
668
    }
669
    var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
670
    var option = locator.findOption(element);
671
    this.browserbot.addSelection(element, option);
672
};
673
674
Selenium.prototype.doRemoveSelection = function(locator, optionLocator) {
675
    /**
676
   * Remove a selection from the set of selected options in a multi-select element using an option locator.
677
   *
678
   * @see #doSelect for details of option locators
679
   *
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)
682
   */
683
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)");
687
    }
688
    var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
689
    var option = locator.findOption(element);
690
    this.browserbot.removeSelection(element, option);
691
};
692
693
Selenium.prototype.doRemoveAllSelections = function(locator) {
694
    /**
695
    * Unselects all of the selected options in a multi-select element.
696
    *
697
    * @param locator an <a href="#locators">element locator</a> identifying a multi-select box
698
    */
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)");
702
    }
703
    for (var i = 0; i < element.options.length; i++) {
704
        this.browserbot.removeSelection(element, element.options[i]);
705
    }
706
}
707
708
Selenium.prototype.doSubmit = function(formLocator) {
709
    /**
710
   * Submit the specified form. This is particularly useful for forms without
711
   * submit buttons, e.g. single-input "Search" forms.
712
   *
713
   * @param formLocator an <a href="#locators">element locator</a> for the form you want to submit
714
   */
715
    var form = this.browserbot.findElement(formLocator);
716
    return this.browserbot.submit(form);
717
718
};
719
720
Selenium.prototype.makePageLoadCondition = function(timeout) {
721
    if (timeout == null) {
722
        timeout = this.defaultTimeout;
723
    }
724
    return Selenium.decorateFunctionWithTimeout(fnBind(this._isNewPageLoaded, this), timeout);
725
};
726
727
Selenium.prototype.doOpen = function(url) {
728
    /**
729
   * Opens an URL in the test frame. This accepts both relative and absolute
730
   * URLs.
731
   *
732
   * The &quot;open&quot; command waits for the page to load before proceeding,
733
   * ie. the &quot;AndWait&quot; suffix is implicit.
734
   *
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.
739
   *
740
   * @param url the URL to open; may be relative or absolute
741
   */
742
    this.browserbot.openLocation(url);
743
    return this.makePageLoadCondition();
744
};
745
746
Selenium.prototype.doOpenWindow = function(url, windowID) {
747
    /**
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
750
   * command.
751
   *
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>
755
   *
756
   * @param url the URL to open, which can be blank
757
   * @param windowID the JavaScript window ID of the window to select
758
   */
759
   this.browserbot.openWindow(url, windowID);
760
};
761
762
Selenium.prototype.doSelectWindow = function(windowID) {
763
    /**
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
766
   * as the target.
767
   *
768
   * <p>Selenium has several strategies for finding the window object referred to by the "windowID" parameter.</p>
769
   *
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>
776
   *
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>
780
   *
781
   * <p><code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"</code></p>
782
   *
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>
786
   *
787
   * @param windowID the JavaScript window ID of the window to select
788
   */
789
    this.browserbot.selectWindow(windowID);
790
};
791
792
Selenium.prototype.doSelectFrame = function(locator) {
793
    /**
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".
797
    *
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>
800
    *
801
    * @param locator an <a href="#locators">element locator</a> identifying a frame or iframe
802
    */
803
        this.browserbot.selectFrame(locator);
804
};
805
806
Selenium.prototype.getLogMessages = function() {
807
    /**
808
        * Return the contents of the log.
809
    *
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>
814
        *
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>
818
    *
819
        * @return string all log messages seen since the last call to this API
820
    */
821
        return "getLogMessages should be implemented in the selenium server";
822
};
823
824
825
Selenium.prototype.getWhetherThisFrameMatchFrameExpression = function(currentFrameString, target) {
826
    /**
827
     * Determine whether current/locator identify the frame containing this running code.
828
     *
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>
834
     *
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
838
     */
839
    var isDom = false;
840
    if (target.indexOf("dom=") == 0) {
841
        target = target.substr(4);
842
        isDom = true;
843
    }
844
    var t;
845
    try {
846
        eval("t=" + currentFrameString + "." + target);
847
    } catch (e) {
848
    }
849
    var autWindow = this.browserbot.getCurrentWindow();
850
    if (t != null) {
851
        if (t.window == autWindow) {
852
            return true;
853
        }
854
        return false;
855
    }
856
    if (isDom) {
857
        return false;
858
    }
859
    var currentFrame;
860
    eval("currentFrame=" + currentFrameString);
861
    if (target == "relative=up") {
862
        if (currentFrame.window.parent == autWindow) {
863
            return true;
864
        }
865
        return false;
866
    }
867
    if (target == "relative=top") {
868
        if (currentFrame.window.top == autWindow) {
869
            return true;
870
        }
871
        return false;
872
    }
873
    if (autWindow.name == target && currentFrame.window == autWindow.parent) {
874
        return true;
875
    }
876
    return false;
877
};
878
879
Selenium.prototype.getWhetherThisWindowMatchWindowExpression = function(currentWindowString, target) {
880
    /**
881
    * Determine whether currentWindowString plus target identify the window containing this running code.
882
     *
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>
888
     *
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
892
     */
893
     if (window.opener!=null && window.opener[target]!=null && window.opener[target]==window) {
894
         return true;
895
     }
896
     return false;
897
};
898
899
Selenium.prototype.doWaitForPopUp = function(windowID, timeout) {
900
    /**
901
    * Waits for a popup window to appear and load up.
902
    *
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
905
    */
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
914
                return false;
915
            }
916
        }
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
920
                // what a world!
921
                LOG.debug("DGF what a world!");
922
                return false;
923
            }
924
        }
925
        if (!targetWindow.document) return false;
926
        if (!selenium.browserbot.getCurrentWindow().document.readyState) {
927
            // This is Firefox, with no readyState extension
928
            return true;
929
        }
930
        if ('complete' != targetWindow.document.readyState) return false;
931
        return true;
932
    };
933
934
    return Selenium.decorateFunctionWithTimeout(popupLoadedPredicate, timeout);
935
}
936
937
Selenium.prototype.doWaitForPopUp.dontCheckAlertsAndConfirms = true;
938
939
Selenium.prototype.doChooseCancelOnNextConfirmation = function() {
940
    /**
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.
945
   *
946
   */
947
    this.browserbot.cancelNextConfirmation();
948
};
949
950
951
Selenium.prototype.doAnswerOnNextPrompt = function(answer) {
952
    /**
953
   * Instructs Selenium to return the specified answer string in response to
954
   * the next JavaScript prompt [window.prompt()].
955
   *
956
   *
957
   * @param answer the answer to give in response to the prompt pop-up
958
   */
959
    this.browserbot.setNextPromptResult(answer);
960
};
961
962
Selenium.prototype.doGoBack = function() {
963
    /**
964
     * Simulates the user clicking the "back" button on their browser.
965
     *
966
     */
967
    this.browserbot.goBack();
968
};
969
970
Selenium.prototype.doRefresh = function() {
971
    /**
972
     * Simulates the user clicking the "Refresh" button on their browser.
973
     *
974
     */
975
    this.browserbot.refresh();
976
};
977
978
Selenium.prototype.doClose = function() {
979
    /**
980
     * Simulates the user clicking the "close" button in the titlebar of a popup
981
     * window or tab.
982
     */
983
    this.browserbot.close();
984
};
985
986
Selenium.prototype.ensureNoUnhandledPopups = function() {
987
    if (this.browserbot.hasAlerts()) {
988
        throw new SeleniumError("There was an unexpected Alert! [" + this.browserbot.getNextAlert() + "]");
989
    }
990
    if ( this.browserbot.hasConfirmations() ) {
991
        throw new SeleniumError("There was an unexpected Confirmation! [" + this.browserbot.getNextConfirmation() + "]");
992
    }
993
};
994
995
Selenium.prototype.isAlertPresent = function() {
996
   /**
997
   * Has an alert occurred?
998
   *
999
   * <p>
1000
   * This function never throws an exception
1001
   * </p>
1002
   * @return boolean true if there is an alert
1003
   */
1004
    return this.browserbot.hasAlerts();
1005
};
1006
1007
Selenium.prototype.isPromptPresent = function() {
1008
   /**
1009
   * Has a prompt occurred?
1010
   *
1011
   * <p>
1012
   * This function never throws an exception
1013
   * </p>
1014
   * @return boolean true if there is a pending prompt
1015
   */
1016
    return this.browserbot.hasPrompts();
1017
};
1018
1019
Selenium.prototype.isConfirmationPresent = function() {
1020
   /**
1021
   * Has confirm() been called?
1022
   *
1023
   * <p>
1024
   * This function never throws an exception
1025
   * </p>
1026
   * @return boolean true if there is a pending confirmation
1027
   */
1028
    return this.browserbot.hasConfirmations();
1029
};
1030
Selenium.prototype.getAlert = function() {
1031
    /**
1032
   * Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.
1033
   *
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
1036
   * will fail.</p>
1037
   *
1038
   * <p>NOTE: under Selenium, JavaScript alerts will NOT pop up a visible alert
1039
   * dialog.</p>
1040
   *
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
1045
   */
1046
    if (!this.browserbot.hasAlerts()) {
1047
        Assert.fail("There were no alerts");
1048
    }
1049
    return this.browserbot.getNextAlert();
1050
};
1051
Selenium.prototype.getAlert.dontCheckAlertsAndConfirms = true;
1052
1053
Selenium.prototype.getConfirmation = function() {
1054
    /**
1055
   * Retrieves the message of a JavaScript confirmation dialog generated during
1056
   * the previous action.
1057
   *
1058
   * <p>
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.
1063
   * </p>
1064
   *
1065
   * <p>
1066
   * NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible
1067
   * dialog.
1068
   * </p>
1069
   *
1070
   * <p>
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
1074
   * OK.
1075
   * </p>
1076
   *
1077
   * @return string the message of the most recent JavaScript confirmation dialog
1078
   */
1079
    if (!this.browserbot.hasConfirmations()) {
1080
        Assert.fail("There were no confirmations");
1081
    }
1082
    return this.browserbot.getNextConfirmation();
1083
};
1084
Selenium.prototype.getConfirmation.dontCheckAlertsAndConfirms = true;
1085
1086
Selenium.prototype.getPrompt = function() {
1087
    /**
1088
   * Retrieves the message of a JavaScript question prompt dialog generated during
1089
   * the previous action.
1090
   *
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>
1094
   *
1095
   * <p>NOTE: under Selenium, JavaScript prompts will NOT pop up a visible
1096
   * dialog.</p>
1097
   *
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
1102
   */
1103
    if (! this.browserbot.hasPrompts()) {
1104
        Assert.fail("There were no prompts");
1105
    }
1106
    return this.browserbot.getNextPrompt();
1107
};
1108
1109
Selenium.prototype.getLocation = function() {
1110
    /** Gets the absolute URL of the current page.
1111
   *
1112
   * @return string the absolute URL of the current page
1113
   */
1114
    return this.browserbot.getCurrentWindow().location;
1115
};
1116
1117
Selenium.prototype.getTitle = function() {
1118
    /** Gets the title of the current page.
1119
   *
1120
   * @return string the title of the current page
1121
   */
1122
    return this.browserbot.getTitle();
1123
};
1124
1125
1126
Selenium.prototype.getBodyText = function() {
1127
    /**
1128
     * Gets the entire text of the page.
1129
     * @return string the entire text of the page
1130
     */
1131
    return this.browserbot.bodyText();
1132
};
1133
1134
1135
Selenium.prototype.getValue = function(locator) {
1136
  /**
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.
1140
   *
1141
   * @param locator an <a href="#locators">element locator</a>
1142
   * @return string the element value, or "on/off" for checkbox/radio elements
1143
   */
1144
    var element = this.browserbot.findElement(locator)
1145
    return getInputValue(element).trim();
1146
}
1147
1148
Selenium.prototype.getText = function(locator) {
1149
    /**
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.
1154
   *
1155
   * @param locator an <a href="#locators">element locator</a>
1156
   * @return string the text of the element
1157
   */
1158
    var element = this.browserbot.findElement(locator);
1159
    return getText(element).trim();
1160
};
1161
1162
Selenium.prototype.doHighlight = function(locator) {
1163
    /**
1164
    * Briefly changes the backgroundColor of the specified element yellow.  Useful for debugging.
1165
    *
1166
    * @param locator an <a href="#locators">element locator</a>
1167
    */
1168
    var element = this.browserbot.findElement(locator);
1169
    this.browserbot.highlight(element, true);
1170
};
1171
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.
1175
   *
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>
1179
   *
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>
1184
   *
1185
   * @param script the JavaScript snippet to run
1186
   * @return string the results of evaluating the snippet
1187
   */
1188
    try {
1189
        var result = eval(script);
1190
        // Selenium RC doesn't allow returning null
1191
        if (null == result) return "null";
1192
        return result;
1193
    } catch (e) {
1194
        throw new SeleniumError("Threw an exception: " + e.message);
1195
    }
1196
};
1197
1198
Selenium.prototype.isChecked = function(locator) {
1199
    /**
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
1203
   */
1204
    var element = this.browserbot.findElement(locator);
1205
    if (element.checked == null) {
1206
        throw new SeleniumError("Element " + locator + " is not a toggle-button.");
1207
    }
1208
    return element.checked;
1209
};
1210
1211
Selenium.prototype.getTable = function(tableCellAddress) {
1212
    /**
1213
   * Gets the text from a cell of a table. The cellAddress syntax
1214
   * tableLocator.row.column, where row and column start at 0.
1215
   *
1216
   * @param tableCellAddress a cell address, e.g. "foo.1.4"
1217
   * @return string the text from the specified cell
1218
   */
1219
    // This regular expression matches "tableName.row.column"
1220
    // For example, "mytable.3.4"
1221
    pattern = /(.*)\.(\d+)\.(\d+)/;
1222
1223
    if(!pattern.test(tableCellAddress)) {
1224
        throw new SeleniumError("Invalid target format. Correct format is tableName.rowNum.columnNum");
1225
    }
1226
1227
    pieces = tableCellAddress.match(pattern);
1228
1229
    tableName = pieces[1];
1230
    row = pieces[2];
1231
    col = pieces[3];
1232
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");
1236
    }
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");
1239
    }
1240
    else {
1241
        actualContent = getText(table.rows[row].cells[col]);
1242
        return actualContent.trim();
1243
    }
1244
    return null;
1245
};
1246
1247
Selenium.prototype.getSelectedLabels = function(selectLocator) {
1248
    /** Gets all option labels (visible text) for selected options in the specified select or multi-select element.
1249
   *
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
1252
   */
1253
    return this.findSelectedOptionProperties(selectLocator, "text").join(",");
1254
}
1255
1256
Selenium.prototype.getSelectedLabel = function(selectLocator) {
1257
    /** Gets option label (visible text) for selected option in the specified select element.
1258
   *
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
1261
   */
1262
    return this.findSelectedOptionProperty(selectLocator, "text");
1263
}
1264
1265
Selenium.prototype.getSelectedValues = function(selectLocator) {
1266
    /** Gets all option values (value attributes) for selected options in the specified select or multi-select element.
1267
   *
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
1270
   */
1271
    return this.findSelectedOptionProperties(selectLocator, "value").join(",");
1272
}
1273
1274
Selenium.prototype.getSelectedValue = function(selectLocator) {
1275
    /** Gets option value (value attribute) for selected option in the specified select element.
1276
   *
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
1279
   */
1280
    return this.findSelectedOptionProperty(selectLocator, "value");
1281
}
1282
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.
1285
   *
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
1288
   */
1289
    return this.findSelectedOptionProperties(selectLocator, "index").join(",");
1290
}
1291
1292
Selenium.prototype.getSelectedIndex = function(selectLocator) {
1293
    /** Gets option index (option number, starting at 0) for selected option in the specified select element.
1294
   *
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
1297
   */
1298
    return this.findSelectedOptionProperty(selectLocator, "index");
1299
}
1300
1301
Selenium.prototype.getSelectedIds = function(selectLocator) {
1302
    /** Gets all option element IDs for selected options in the specified select or multi-select element.
1303
   *
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
1306
   */
1307
    return this.findSelectedOptionProperties(selectLocator, "id").join(",");
1308
}
1309
1310
Selenium.prototype.getSelectedId = function(selectLocator) {
1311
    /** Gets option element ID for selected option in the specified select element.
1312
   *
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
1315
   */
1316
    return this.findSelectedOptionProperty(selectLocator, "id");
1317
}
1318
1319
Selenium.prototype.isSomethingSelected = function(selectLocator) {
1320
    /** Determines whether some option in a drop-down menu is selected.
1321
   *
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
1324
   */
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)");
1328
    }
1329
1330
    var selectedOptions = [];
1331
1332
    for (var i = 0; i < element.options.length; i++) {
1333
        if (element.options[i].selected)
1334
        {
1335
            return true;
1336
        }
1337
    }
1338
    return false;
1339
}
1340
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)");
1345
    }
1346
1347
    var selectedOptions = [];
1348
1349
    for (var i = 0; i < element.options.length; i++) {
1350
        if (element.options[i].selected)
1351
        {
1352
            var propVal = element.options[i][property];
1353
            if (propVal.replace) {
1354
                propVal.replace(/,/g, "\\,");
1355
            }
1356
            selectedOptions.push(propVal);
1357
        }
1358
    }
1359
    if (selectedOptions.length == 0) Assert.fail("No option selected");
1360
    return selectedOptions;
1361
}
1362
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!");
1367
    }
1368
    return selectedOptions[0];
1369
}
1370
1371
Selenium.prototype.getSelectOptions = function(selectLocator) {
1372
    /** Gets all option labels in the specified select drop-down.
1373
   *
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
1376
   */
1377
    var element = this.browserbot.findElement(selectLocator);
1378
1379
    var selectOptions = [];
1380
1381
    for (var i = 0; i < element.options.length; i++) {
1382
        var option = element.options[i].text.replace(/,/g, "\\,");
1383
        selectOptions.push(option);
1384
    }
1385
1386
    return selectOptions.join(",");
1387
};
1388
1389
1390
Selenium.prototype.getAttribute = function(attributeLocator) {
1391
    /**
1392
   * Gets the value of an element attribute.
1393
   *
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
1396
   */
1397
   var result = this.browserbot.findAttribute(attributeLocator);
1398
   if (result == null) {
1399
           throw new SeleniumError("Could not find element attribute: " + attributeLocator);
1400
    }
1401
    return result;
1402
};
1403
1404
Selenium.prototype.isTextPresent = function(pattern) {
1405
    /**
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
1409
   */
1410
    var allText = this.browserbot.bodyText();
1411
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:"
1416
                }
1417
        patternMatcher.matcher = new PatternMatcher.strategies.globContains(pattern);
1418
    }
1419
    else if (patternMatcher.strategy == PatternMatcher.strategies.exact) {
1420
                pattern = pattern.substring("exact:".length); // strip off "exact:"
1421
        return allText.indexOf(pattern) != -1;
1422
    }
1423
    return patternMatcher.matches(allText);
1424
};
1425
1426
Selenium.prototype.isElementPresent = function(locator) {
1427
    /**
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
1431
   */
1432
    try {
1433
        this.browserbot.findElement(locator);
1434
    } catch (e) {
1435
        return false;
1436
    }
1437
    return true;
1438
};
1439
1440
Selenium.prototype.isVisible = function(locator) {
1441
    /**
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.
1447
   *
1448
   * @param locator an <a href="#locators">element locator</a>
1449
   * @return boolean true if the specified element is visible, false otherwise
1450
   */
1451
    var element;
1452
    element = this.browserbot.findElement(locator);
1453
    var visibility = this.findEffectiveStyleProperty(element, "visibility");
1454
    var _isDisplayed = this._isDisplayed(element);
1455
    return (visibility != "hidden" && _isDisplayed);
1456
};
1457
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);
1463
    }
1464
    return propertyValue;
1465
};
1466
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);
1472
    }
1473
    return true;
1474
};
1475
1476
Selenium.prototype.findEffectiveStyle = function(element) {
1477
    if (element.style == undefined) {
1478
        return undefined; // not a styled element
1479
    }
1480
    var window = this.browserbot.getCurrentWindow();
1481
    if (window.getComputedStyle) {
1482
        // DOM-Level-2-CSS
1483
        return window.getComputedStyle(element, null);
1484
    }
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"
1491
    }
1492
    throw new SeleniumError("cannot determine effective stylesheet in this browser");
1493
};
1494
1495
Selenium.prototype.isEditable = function(locator) {
1496
    /**
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.
1499
   *
1500
   * @param locator an <a href="#locators">element locator</a>
1501
   * @return boolean true if the input element is editable, false otherwise
1502
   */
1503
    var element = this.browserbot.findElement(locator);
1504
    if (element.value == undefined) {
1505
        Assert.fail("Element " + locator + " is not an input.");
1506
    }
1507
    return !element.disabled;
1508
};
1509
1510
Selenium.prototype.getAllButtons = function() {
1511
    /** Returns the IDs of all buttons on the page.
1512
   *
1513
   * <p>If a given button has no ID, it will appear as "" in this array.</p>
1514
   *
1515
   * @return string[] the IDs of all buttons on the page
1516
   */
1517
   return this.browserbot.getAllButtons();
1518
};
1519
1520
Selenium.prototype.getAllLinks = function() {
1521
    /** Returns the IDs of all links on the page.
1522
   *
1523
   * <p>If a given link has no ID, it will appear as "" in this array.</p>
1524
   *
1525
   * @return string[] the IDs of all links on the page
1526
   */
1527
   return this.browserbot.getAllLinks();
1528
};
1529
1530
Selenium.prototype.getAllFields = function() {
1531
    /** Returns the IDs of all input fields on the page.
1532
   *
1533
   * <p>If a given field has no ID, it will appear as "" in this array.</p>
1534
   *
1535
   * @return string[] the IDs of all field on the page
1536
   */
1537
   return this.browserbot.getAllFields();
1538
};
1539
1540
Selenium.prototype.getAttributeFromAllWindows = function(attributeName) {
1541
    /** Returns every instance of some attribute from all known windows.
1542
    *
1543
    * @param attributeName name of an attribute on the windows
1544
    * @return string[] the set of values of this attribute from all known windows.
1545
    */
1546
    var attributes = new Array();
1547
1548
    var win = selenium.browserbot.topWindow;
1549
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)
1555
    {
1556
        try {
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.
1560
    }
1561
    return attributes;
1562
};
1563
1564
Selenium.prototype.findWindow = function(soughtAfterWindowPropertyValue) {
1565
   var targetPropertyName = "name";
1566
   if (soughtAfterWindowPropertyValue.match("^title=")) {
1567
       targetPropertyName = "document.title";
1568
        soughtAfterWindowPropertyValue = soughtAfterWindowPropertyValue.replace(/^title=/, "");
1569
   }
1570
   else {
1571
       // matching "name":
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();
1578
        }
1579
   }
1580
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;
1586
   }
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;
1591
        }
1592
   }
1593
   throw new SeleniumError("could not find window with property " + targetPropertyName + " matching " + soughtAfterWindowPropertyValue);
1594
};
1595
1596
Selenium.prototype.doDragdrop = function(locator, movementsString) {
1597
/** deprecated - use dragAndDrop instead
1598
   *
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"
1601
   */
1602
   this.doDragAndDrop(locator, movementsString);
1603
};
1604
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>
1610
    *
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
1614
    */
1615
    this.mouseSpeed = pixels;
1616
}
1617
1618
Selenium.prototype.getMouseSpeed = function() {
1619
    /** Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
1620
    *
1621
    * @return number the number of pixels between "mousemove" events during dragAndDrop commands (default=10)
1622
    */
1623
    this.mouseSpeed = pixels;
1624
}
1625
1626
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"
1631
    */
1632
    var element = this.browserbot.findElement(locator);
1633
    var clientStartXY = getClientXY(element)
1634
    var clientStartX = clientStartXY[0];
1635
    var clientStartY = clientStartXY[1];
1636
1637
    var movements = movementsString.split(/,/);
1638
    var movementX = Number(movements[0]);
1639
    var movementY = Number(movements[1]);
1640
1641
    var clientFinishX = ((clientStartX + movementX) < 0) ? 0 : (clientStartX + movementX);
1642
    var clientFinishY = ((clientStartY + movementY) < 0) ? 0 : (clientStartY + movementY);
1643
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;
1649
    }
1650
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;
1655
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);
1660
    }
1661
1662
    this.browserbot.triggerMouseEvent(element, 'mousemove',   true, clientFinishX, clientFinishY);
1663
    this.browserbot.triggerMouseEvent(element, 'mouseup',   true, clientFinishX, clientFinishY);
1664
};
1665
1666
Selenium.prototype.doDragAndDropToObject = function(locatorOfObjectToBeDragged, locatorOfDragDestinationObject) {
1667
/** Drags an element and drops it on another element
1668
   *
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
1671
   */
1672
   var startX = this.getElementPositionLeft(locatorOfObjectToBeDragged);
1673
   var startY = this.getElementPositionTop(locatorOfObjectToBeDragged);
1674
1675
   var destinationLeftX = this.getElementPositionLeft(locatorOfDragDestinationObject);
1676
   var destinationTopY = this.getElementPositionTop(locatorOfDragDestinationObject);
1677
   var destinationWidth = this.getElementWidth(locatorOfDragDestinationObject);
1678
   var destinationHeight = this.getElementHeight(locatorOfDragDestinationObject);
1679
1680
   var endX = Math.round(destinationLeftX + (destinationWidth / 2));
1681
   var endY = Math.round(destinationTopY + (destinationHeight / 2));
1682
1683
   var deltaX = endX - startX;
1684
   var deltaY = endY - startY;
1685
1686
   var movementsString = "" + deltaX + "," + deltaY;
1687
1688
   this.doDragAndDrop(locatorOfObjectToBeDragged, movementsString);
1689
};
1690
1691
Selenium.prototype.doWindowFocus = function(windowName) {
1692
/** Gives focus to a window
1693
   *
1694
   * @param windowName name of the window to be given focus
1695
   */
1696
   this.findWindow(windowName).focus();
1697
};
1698
1699
1700
Selenium.prototype.doWindowMaximize = function(windowName) {
1701
/** Resize window to take up the entire screen
1702
   *
1703
   * @param windowName name of the window to be enlarged
1704
   */
1705
   var window = this.findWindow(windowName);
1706
   if (window!=null && window.screen) {
1707
       window.moveTo(0,0);
1708
        window.outerHeight = screen.availHeight;
1709
        window.outerWidth = screen.availWidth;
1710
   }
1711
};
1712
1713
Selenium.prototype.getAllWindowIds = function() {
1714
  /** Returns the IDs of all windows that the browser knows about.
1715
   *
1716
   * @return string[] the IDs of all windows that the browser knows about.
1717
   */
1718
   return this.getAttributeFromAllWindows("id");
1719
};
1720
1721
Selenium.prototype.getAllWindowNames = function() {
1722
  /** Returns the names of all windows that the browser knows about.
1723
   *
1724
   * @return string[] the names of all windows that the browser knows about.
1725
   */
1726
   return this.getAttributeFromAllWindows("name");
1727
};
1728
1729
Selenium.prototype.getAllWindowTitles = function() {
1730
  /** Returns the titles of all windows that the browser knows about.
1731
   *
1732
   * @return string[] the titles of all windows that the browser knows about.
1733
   */
1734
   return this.getAttributeFromAllWindows("document.title");
1735
};
1736
1737
Selenium.prototype.getHtmlSource = function() {
1738
    /** Returns the entire HTML source between the opening and
1739
   * closing "html" tags.
1740
   *
1741
   * @return string the entire HTML source
1742
   */
1743
    return this.browserbot.getDocument().getElementsByTagName("html")[0].innerHTML;
1744
};
1745
1746
Selenium.prototype.doSetCursorPosition = function(locator, position) {
1747
    /**
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.
1750
   *
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.
1753
   */
1754
   var element = this.browserbot.findElement(locator);
1755
    if (element.value == undefined) {
1756
        Assert.fail("Element " + locator + " is not an input.");
1757
    }
1758
    if (position == -1) {
1759
        position = element.value.length;
1760
    }
1761
1762
   if( element.setSelectionRange && !browserVersion.isOpera) {
1763
       element.focus();
1764
        element.setSelectionRange(/*start*/position,/*end*/position);
1765
   }
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);
1772
      range.select();
1773
   }
1774
}
1775
1776
Selenium.prototype.getElementIndex = function(locator) {
1777
    /**
1778
     * Get the relative index of an element to its parent (starting from 0). The comment node and empty text node
1779
     * will be ignored.
1780
     *
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)
1783
     */
1784
    var element = this.browserbot.findElement(locator);
1785
    var previousSibling;
1786
    var index = 0;
1787
    while ((previousSibling = element.previousSibling) != null) {
1788
        if (!this._isCommentOrEmptyTextNode(previousSibling)) {
1789
            index++;
1790
        }
1791
        element = previousSibling;
1792
    }
1793
    return index;
1794
}
1795
1796
Selenium.prototype.isOrdered = function(locator1, locator2) {
1797
    /**
1798
     * Check if these two elements have same parent and are ordered. Two same elements will
1799
     * not be considered ordered.
1800
     *
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
1804
     */
1805
    var element1 = this.browserbot.findElement(locator1);
1806
    var element2 = this.browserbot.findElement(locator2);
1807
    if (element1 === element2) return false;
1808
1809
    var previousSibling;
1810
    while ((previousSibling = element2.previousSibling) != null) {
1811
        if (previousSibling === element1) {
1812
            return true;
1813
        }
1814
        element2 = previousSibling;
1815
    }
1816
    return false;
1817
}
1818
1819
Selenium.prototype._isCommentOrEmptyTextNode = function(node) {
1820
    return node.nodeType == 8 || ((node.nodeType == 3) && !(/[^\t\n\r ]/.test(node.data)));
1821
}
1822
1823
Selenium.prototype.getElementPositionLeft = function(locator) {
1824
   /**
1825
   * Retrieves the horizontal position of an element
1826
   *
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.
1829
   */
1830
       var element;
1831
        if ("string"==typeof locator) {
1832
            element = this.browserbot.findElement(locator);
1833
        }
1834
        else {
1835
            element = locator;
1836
        }
1837
    var x = element.offsetLeft;
1838
    var elementParent = element.offsetParent;
1839
1840
    while (elementParent != null)
1841
    {
1842
        if(document.all)
1843
        {
1844
            if( (elementParent.tagName != "TABLE") && (elementParent.tagName != "BODY") )
1845
            {
1846
                x += elementParent.clientLeft;
1847
            }
1848
        }
1849
        else // Netscape/DOM
1850
        {
1851
            if(elementParent.tagName == "TABLE")
1852
            {
1853
                var parentBorder = parseInt(elementParent.border);
1854
                if(isNaN(parentBorder))
1855
                {
1856
                    var parentFrame = elementParent.getAttribute('frame');
1857
                    if(parentFrame != null)
1858
                    {
1859
                        x += 1;
1860
                    }
1861
                }
1862
                else if(parentBorder > 0)
1863
                {
1864
                    x += parentBorder;
1865
                }
1866
            }
1867
        }
1868
        x += elementParent.offsetLeft;
1869
        elementParent = elementParent.offsetParent;
1870
    }
1871
    return x;
1872
};
1873
1874
Selenium.prototype.getElementPositionTop = function(locator) {
1875
   /**
1876
   * Retrieves the vertical position of an element
1877
   *
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.
1880
   */
1881
       var element;
1882
        if ("string"==typeof locator) {
1883
            element = this.browserbot.findElement(locator);
1884
        }
1885
        else {
1886
            element = locator;
1887
        }
1888
1889
       var y = 0;
1890
1891
       while (element != null)
1892
    {
1893
        if(document.all)
1894
        {
1895
            if( (element.tagName != "TABLE") && (element.tagName != "BODY") )
1896
            {
1897
            y += element.clientTop;
1898
            }
1899
        }
1900
        else // Netscape/DOM
1901
        {
1902
            if(element.tagName == "TABLE")
1903
            {
1904
            var parentBorder = parseInt(element.border);
1905
            if(isNaN(parentBorder))
1906
            {
1907
                var parentFrame = element.getAttribute('frame');
1908
                if(parentFrame != null)
1909
                {
1910
                    y += 1;
1911
                }
1912
            }
1913
            else if(parentBorder > 0)
1914
            {
1915
                y += parentBorder;
1916
            }
1917
            }
1918
        }
1919
        y += element.offsetTop;
1920
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)
1925
            {
1926
                // skip the parent that's too small
1927
                element = element.offsetParent.offsetParent;
1928
            }
1929
            else
1930
            {
1931
            // Next up...
1932
            element = element.offsetParent;
1933
        }
1934
       }
1935
    return y;
1936
};
1937
1938
Selenium.prototype.getElementWidth = function(locator) {
1939
   /**
1940
   * Retrieves the width of an element
1941
   *
1942
   * @param locator an <a href="#locators">element locator</a> pointing to an element
1943
   * @return number width of an element in pixels
1944
   */
1945
   var element = this.browserbot.findElement(locator);
1946
   return element.offsetWidth;
1947
};
1948
1949
Selenium.prototype.getElementHeight = function(locator) {
1950
   /**
1951
   * Retrieves the height of an element
1952
   *
1953
   * @param locator an <a href="#locators">element locator</a> pointing to an element
1954
   * @return number height of an element in pixels
1955
   */
1956
   var element = this.browserbot.findElement(locator);
1957
   return element.offsetHeight;
1958
};
1959
1960
Selenium.prototype.getCursorPosition = function(locator) {
1961
    /**
1962
   * Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers.
1963
   *
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.
1967
   *
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
1970
   */
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){
1975
        try {
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);
1983
        } catch (e) {
1984
            Assert.fail("There is no cursor on this page!");
1985
        }
1986
        var answer = String(elementRange.text).replace(/\r/g,"").length;
1987
        return answer;
1988
    } else {
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!");
1992
            }
1993
            return element.selectionStart;
1994
        }
1995
    }
1996
    throw new Error("Couldn't detect cursor position on this browser!");
1997
}
1998
1999
2000
Selenium.prototype.doSetContext = function(context, logLevelThreshold) {
2001
    /**
2002
   * Writes a message to the status bar and adds a note to the browser-side
2003
   * log.
2004
   *
2005
   * <p>If logLevelThreshold is specified, set the threshold for logging
2006
   * to that level (debug, info, warn, error).</p>
2007
   *
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>
2010
   *
2011
   * @param context
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
2014
   */
2015
    if  (logLevelThreshold==null || logLevelThreshold=="") {
2016
        return this.browserbot.setContext(context);
2017
    }
2018
    return this.browserbot.setContext(context, logLevelThreshold);
2019
};
2020
2021
Selenium.prototype.getExpression = function(expression) {
2022
    /**
2023
     * Returns the specified expression.
2024
     *
2025
     * <p>This is useful because of JavaScript preprocessing.
2026
     * It is used to generate commands like assertExpression and waitForExpression.</p>
2027
     *
2028
     * @param expression the value to return
2029
     * @return string the value passed in
2030
     */
2031
    return expression;
2032
}
2033
2034
Selenium.prototype.doWaitForCondition = function(script, timeout) {
2035
    /**
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.
2039
   *
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
2046
   */
2047
    return Selenium.decorateFunctionWithTimeout(function () {
2048
        return eval(script);
2049
    }, timeout);
2050
};
2051
2052
Selenium.prototype.doWaitForCondition.dontCheckAlertsAndConfirms = true;
2053
2054
Selenium.prototype.doSetTimeout = function(timeout) {
2055
    /**
2056
     * Specifies the amount of time that Selenium will wait for actions to complete.
2057
     *
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
2061
     */
2062
    if (!timeout) {
2063
        timeout = Selenium.DEFAULT_TIMEOUT;
2064
    }
2065
    this.defaultTimeout = timeout;
2066
}
2067
2068
Selenium.prototype.doWaitForPageToLoad = function(timeout) {
2069
    /**
2070
     * Waits for a new page to load.
2071
     *
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>
2074
     *
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
2080
     */
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);
2084
    }
2085
};
2086
2087
Selenium.prototype._isNewPageLoaded = function() {
2088
    return this.browserbot.isNewPageLoaded();
2089
};
2090
2091
Selenium.prototype.doWaitForPageToLoad.dontCheckAlertsAndConfirms = true;
2092
2093
/**
2094
 * Evaluate a parameter, performing JavaScript evaluation and variable substitution.
2095
 * If the string matches the pattern "javascript{ ... }", evaluate the string between the braces.
2096
 */
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();
2101
    }
2102
    return this.replaceVariables(value);
2103
};
2104
2105
/*
2106
 * Search through str and replace all variable references ${varName} with their
2107
 * value in storedVars.
2108
 */
2109
Selenium.prototype.replaceVariables = function(str) {
2110
    var stringResult = str;
2111
2112
    // Find all of the matching variable references
2113
    var match = stringResult.match(/\$\{\w+\}/g);
2114
    if (!match) {
2115
        return stringResult;
2116
    }
2117
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);
2125
        }
2126
    }
2127
    return stringResult;
2128
};
2129
2130
Selenium.prototype.getCookie = function() {
2131
    /**
2132
     * Return all cookies of the current page under test.
2133
     *
2134
     * @return string all cookies of the current page under test
2135
     */
2136
    var doc = this.browserbot.getDocument();
2137
    return doc.cookie;
2138
};
2139
2140
Selenium.prototype.doCreateCookie = function(nameValuePair, optionsString) {
2141
    /**
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.
2144
     *
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.
2149
     */
2150
    var results = /[^\s=\[\]\(\),"\/\?@:;]+=[^\s=\[\]\(\),"\/\?@:;]*/.test(nameValuePair);
2151
    if (!results) {
2152
        throw new SeleniumError("Invalid parameter.");
2153
    }
2154
    var cookie = nameValuePair.trim();
2155
    results = /max_age=(\d+)/.exec(optionsString);
2156
    if (results) {
2157
        var expireDateInMilliseconds = (new Date()).getTime() + results[1] * 1000;
2158
        cookie += "; expires=" + new Date(expireDateInMilliseconds).toGMTString();
2159
    }
2160
    results = /path=([^\s,]+)[,]?/.exec(optionsString);
2161
    if (results) {
2162
        var path = results[1];
2163
        if (browserVersion.khtml) {
2164
            // Safari and conquerer don't like paths with / at the end
2165
            if ("/" != path) {
2166
                path = path.replace(/\/$/, "");
2167
            }
2168
        }
2169
        cookie += "; path=" + path;
2170
    }
2171
    LOG.debug("Setting cookie to: " + cookie);
2172
    this.browserbot.getDocument().cookie = cookie;
2173
}
2174
2175
Selenium.prototype.doDeleteCookie = function(name,path) {
2176
    /**
2177
     * Delete a named cookie with specified path.
2178
     *
2179
     * @param name the name of the cookie to be deleted
2180
     * @param path the path property of the cookie to be deleted
2181
     */
2182
    // set the expire time of the cookie to be deleted to one minute before now.
2183
    path = path.trim();
2184
    if (browserVersion.khtml) {
2185
        // Safari and conquerer don't like paths with / at the end
2186
        if ("/" != path) {
2187
            path = path.replace(/\/$/, "");
2188
        }
2189
    }
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;
2194
}
2195
2196
2197
/**
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).
2208
 */
2209
function OptionLocatorFactory() {
2210
}
2211
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]+)=(.*)/);
2217
    if (result) {
2218
        locatorType = result[1];
2219
        locatorValue = result[2];
2220
    }
2221
    if (this.optionLocators == undefined) {
2222
        this.registerOptionLocators();
2223
    }
2224
    if (this.optionLocators[locatorType]) {
2225
        return new this.optionLocators[locatorType](locatorValue);
2226
    }
2227
    throw new SeleniumError("Unkown option locator type: " + locatorType);
2228
};
2229
2230
/**
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".
2235
 */
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];
2243
      }
2244
    }
2245
};
2246
2247
/**
2248
 *  OptionLocator for options identified by their labels.
2249
 */
2250
OptionLocatorFactory.prototype.OptionLocatorByLabel = function(label) {
2251
    this.label = 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];
2257
            }
2258
        }
2259
        throw new SeleniumError("Option with label '" + this.label + "' not found");
2260
    };
2261
2262
    this.assertSelected = function(element) {
2263
        var selectedLabel = element.options[element.selectedIndex].text;
2264
        Assert.matches(this.label, selectedLabel)
2265
    };
2266
};
2267
2268
/**
2269
 *  OptionLocator for options identified by their values.
2270
 */
2271
OptionLocatorFactory.prototype.OptionLocatorByValue = function(value) {
2272
    this.value = 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];
2278
            }
2279
        }
2280
        throw new SeleniumError("Option with value '" + this.value + "' not found");
2281
    };
2282
2283
    this.assertSelected = function(element) {
2284
        var selectedValue = element.options[element.selectedIndex].value;
2285
        Assert.matches(this.value, selectedValue)
2286
    };
2287
};
2288
2289
/**
2290
 *  OptionLocator for options identified by their index.
2291
 */
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);
2296
    }
2297
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");
2301
        }
2302
        return element.options[this.index];
2303
    };
2304
2305
    this.assertSelected = function(element) {
2306
        Assert.equals(this.index, element.selectedIndex);
2307
    };
2308
};
2309
2310
/**
2311
 *  OptionLocator for options identified by their id.
2312
 */
2313
OptionLocatorFactory.prototype.OptionLocatorById = function(id) {
2314
    this.id = 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];
2320
            }
2321
        }
2322
        throw new SeleniumError("Option with id '" + this.id + "' not found");
2323
    };
2324
2325
    this.assertSelected = function(element) {
2326
        var selectedId = element.options[element.selectedIndex].id;
2327
        Assert.matches(this.id, selectedId)
2328
    };
2329
};