rainux-selenium-webdriver 0.0.17

Sign up to get free protection for your applications and to get access to all the features.
Files changed (192) hide show
  1. data/COPYING +204 -0
  2. data/chrome/prebuilt/Win32/Release/npchromedriver.dll +0 -0
  3. data/chrome/prebuilt/x64/Release/npchromedriver.dll +0 -0
  4. data/chrome/src/extension/background.html +9 -0
  5. data/chrome/src/extension/background.js +995 -0
  6. data/chrome/src/extension/content_script.js +1321 -0
  7. data/chrome/src/extension/icons/busy.png +0 -0
  8. data/chrome/src/extension/icons/free.png +0 -0
  9. data/chrome/src/extension/manifest-nonwin.json +19 -0
  10. data/chrome/src/extension/manifest-win.json +20 -0
  11. data/chrome/src/extension/utils.js +231 -0
  12. data/chrome/src/rb/lib/selenium/webdriver/chrome.rb +8 -0
  13. data/chrome/src/rb/lib/selenium/webdriver/chrome/bridge.rb +358 -0
  14. data/chrome/src/rb/lib/selenium/webdriver/chrome/command_executor.rb +124 -0
  15. data/chrome/src/rb/lib/selenium/webdriver/chrome/launcher.rb +135 -0
  16. data/common/src/js/abstractcommandprocessor.js +134 -0
  17. data/common/src/js/asserts.js +296 -0
  18. data/common/src/js/by.js +149 -0
  19. data/common/src/js/command.js +304 -0
  20. data/common/src/js/context.js +58 -0
  21. data/common/src/js/core/Blank.html +7 -0
  22. data/common/src/js/core/InjectedRemoteRunner.html +8 -0
  23. data/common/src/js/core/RemoteRunner.html +101 -0
  24. data/common/src/js/core/SeleniumLog.html +109 -0
  25. data/common/src/js/core/TestPrompt.html +145 -0
  26. data/common/src/js/core/TestRunner-splash.html +55 -0
  27. data/common/src/js/core/TestRunner.html +165 -0
  28. data/common/src/js/core/icons/all.png +0 -0
  29. data/common/src/js/core/icons/continue.png +0 -0
  30. data/common/src/js/core/icons/continue_disabled.png +0 -0
  31. data/common/src/js/core/icons/pause.png +0 -0
  32. data/common/src/js/core/icons/pause_disabled.png +0 -0
  33. data/common/src/js/core/icons/selected.png +0 -0
  34. data/common/src/js/core/icons/step.png +0 -0
  35. data/common/src/js/core/icons/step_disabled.png +0 -0
  36. data/common/src/js/core/lib/cssQuery/cssQuery-p.js +6 -0
  37. data/common/src/js/core/lib/cssQuery/src/cssQuery-level2.js +142 -0
  38. data/common/src/js/core/lib/cssQuery/src/cssQuery-level3.js +150 -0
  39. data/common/src/js/core/lib/cssQuery/src/cssQuery-standard.js +53 -0
  40. data/common/src/js/core/lib/cssQuery/src/cssQuery.js +356 -0
  41. data/common/src/js/core/lib/prototype.js +2006 -0
  42. data/common/src/js/core/lib/scriptaculous/builder.js +101 -0
  43. data/common/src/js/core/lib/scriptaculous/controls.js +815 -0
  44. data/common/src/js/core/lib/scriptaculous/dragdrop.js +915 -0
  45. data/common/src/js/core/lib/scriptaculous/effects.js +958 -0
  46. data/common/src/js/core/lib/scriptaculous/scriptaculous.js +47 -0
  47. data/common/src/js/core/lib/scriptaculous/slider.js +283 -0
  48. data/common/src/js/core/lib/scriptaculous/unittest.js +383 -0
  49. data/common/src/js/core/lib/snapsie.js +91 -0
  50. data/common/src/js/core/scripts/find_matching_child.js +69 -0
  51. data/common/src/js/core/scripts/htmlutils.js +8716 -0
  52. data/common/src/js/core/scripts/injection.html +72 -0
  53. data/common/src/js/core/scripts/selenium-api.js +3291 -0
  54. data/common/src/js/core/scripts/selenium-browserbot.js +2457 -0
  55. data/common/src/js/core/scripts/selenium-browserdetect.js +153 -0
  56. data/common/src/js/core/scripts/selenium-commandhandlers.js +379 -0
  57. data/common/src/js/core/scripts/selenium-executionloop.js +175 -0
  58. data/common/src/js/core/scripts/selenium-logging.js +148 -0
  59. data/common/src/js/core/scripts/selenium-remoterunner.js +695 -0
  60. data/common/src/js/core/scripts/selenium-testrunner.js +1362 -0
  61. data/common/src/js/core/scripts/selenium-version.js +5 -0
  62. data/common/src/js/core/scripts/ui-doc.html +808 -0
  63. data/common/src/js/core/scripts/ui-element.js +1644 -0
  64. data/common/src/js/core/scripts/ui-map-sample.js +979 -0
  65. data/common/src/js/core/scripts/user-extensions.js +3 -0
  66. data/common/src/js/core/scripts/user-extensions.js.sample +75 -0
  67. data/common/src/js/core/scripts/xmlextras.js +153 -0
  68. data/common/src/js/core/selenium-logo.png +0 -0
  69. data/common/src/js/core/selenium-test.css +43 -0
  70. data/common/src/js/core/selenium.css +316 -0
  71. data/common/src/js/core/xpath/dom.js +566 -0
  72. data/common/src/js/core/xpath/javascript-xpath-0.1.11.js +2816 -0
  73. data/common/src/js/core/xpath/util.js +549 -0
  74. data/common/src/js/core/xpath/xmltoken.js +149 -0
  75. data/common/src/js/core/xpath/xpath.js +2481 -0
  76. data/common/src/js/extension/README +2 -0
  77. data/common/src/js/extension/dommessenger.js +152 -0
  78. data/common/src/js/factory.js +55 -0
  79. data/common/src/js/future.js +141 -0
  80. data/common/src/js/jsunit.js +40 -0
  81. data/common/src/js/jsunit/app/css/jsUnitStyle.css +50 -0
  82. data/common/src/js/jsunit/app/css/readme +10 -0
  83. data/common/src/js/jsunit/app/emptyPage.html +11 -0
  84. data/common/src/js/jsunit/app/jsUnitCore.js +534 -0
  85. data/common/src/js/jsunit/app/jsUnitMockTimeout.js +81 -0
  86. data/common/src/js/jsunit/app/jsUnitTestManager.js +705 -0
  87. data/common/src/js/jsunit/app/jsUnitTestSuite.js +44 -0
  88. data/common/src/js/jsunit/app/jsUnitTracer.js +102 -0
  89. data/common/src/js/jsunit/app/jsUnitVersionCheck.js +59 -0
  90. data/common/src/js/jsunit/app/main-counts-errors.html +12 -0
  91. data/common/src/js/jsunit/app/main-counts-failures.html +13 -0
  92. data/common/src/js/jsunit/app/main-counts-runs.html +13 -0
  93. data/common/src/js/jsunit/app/main-counts.html +21 -0
  94. data/common/src/js/jsunit/app/main-data.html +178 -0
  95. data/common/src/js/jsunit/app/main-errors.html +23 -0
  96. data/common/src/js/jsunit/app/main-frame.html +19 -0
  97. data/common/src/js/jsunit/app/main-loader.html +45 -0
  98. data/common/src/js/jsunit/app/main-progress.html +25 -0
  99. data/common/src/js/jsunit/app/main-results.html +67 -0
  100. data/common/src/js/jsunit/app/main-status.html +13 -0
  101. data/common/src/js/jsunit/app/testContainer.html +16 -0
  102. data/common/src/js/jsunit/app/testContainerController.html +77 -0
  103. data/common/src/js/jsunit/app/xbDebug.js +306 -0
  104. data/common/src/js/jsunit/changelog.txt +60 -0
  105. data/common/src/js/jsunit/css/jsUnitStyle.css +83 -0
  106. data/common/src/js/jsunit/images/green.gif +0 -0
  107. data/common/src/js/jsunit/images/logo_jsunit.gif +0 -0
  108. data/common/src/js/jsunit/images/powerby-transparent.gif +0 -0
  109. data/common/src/js/jsunit/images/red.gif +0 -0
  110. data/common/src/js/jsunit/licenses/JDOM_license.txt +56 -0
  111. data/common/src/js/jsunit/licenses/Jetty_license.html +213 -0
  112. data/common/src/js/jsunit/licenses/MPL-1.1.txt +470 -0
  113. data/common/src/js/jsunit/licenses/gpl-2.txt +340 -0
  114. data/common/src/js/jsunit/licenses/index.html +141 -0
  115. data/common/src/js/jsunit/licenses/lgpl-2.1.txt +504 -0
  116. data/common/src/js/jsunit/licenses/mpl-tri-license-c.txt +35 -0
  117. data/common/src/js/jsunit/licenses/mpl-tri-license-html.txt +35 -0
  118. data/common/src/js/jsunit/readme.txt +19 -0
  119. data/common/src/js/jsunit/testRunner.html +167 -0
  120. data/common/src/js/jsunit/version.txt +1 -0
  121. data/common/src/js/key.js +117 -0
  122. data/common/src/js/localcommandprocessor.js +185 -0
  123. data/common/src/js/testcase.js +217 -0
  124. data/common/src/js/timing.js +89 -0
  125. data/common/src/js/webdriver.js +890 -0
  126. data/common/src/js/webelement.js +485 -0
  127. data/common/src/rb/README +30 -0
  128. data/common/src/rb/lib/selenium-webdriver.rb +1 -0
  129. data/common/src/rb/lib/selenium/webdriver.rb +67 -0
  130. data/common/src/rb/lib/selenium/webdriver/bridge_helper.rb +91 -0
  131. data/common/src/rb/lib/selenium/webdriver/child_process.rb +180 -0
  132. data/common/src/rb/lib/selenium/webdriver/core_ext/dir.rb +41 -0
  133. data/common/src/rb/lib/selenium/webdriver/driver.rb +252 -0
  134. data/common/src/rb/lib/selenium/webdriver/driver_extensions/takes_screenshot.rb +24 -0
  135. data/common/src/rb/lib/selenium/webdriver/element.rb +262 -0
  136. data/common/src/rb/lib/selenium/webdriver/error.rb +67 -0
  137. data/common/src/rb/lib/selenium/webdriver/find.rb +89 -0
  138. data/common/src/rb/lib/selenium/webdriver/keys.rb +84 -0
  139. data/common/src/rb/lib/selenium/webdriver/navigation.rb +27 -0
  140. data/common/src/rb/lib/selenium/webdriver/options.rb +50 -0
  141. data/common/src/rb/lib/selenium/webdriver/platform.rb +86 -0
  142. data/common/src/rb/lib/selenium/webdriver/target_locator.rb +70 -0
  143. data/firefox/prebuilt/Win32/Release/webdriver-firefox.dll +0 -0
  144. data/firefox/prebuilt/linux/Release/libwebdriver-firefox.so +0 -0
  145. data/firefox/prebuilt/linux/Release/x_ignore_nofocus.so +0 -0
  146. data/firefox/prebuilt/linux64/Release/libwebdriver-firefox.so +0 -0
  147. data/firefox/prebuilt/linux64/Release/x_ignore_nofocus.so +0 -0
  148. data/firefox/prebuilt/nsICommandProcessor.xpt +0 -0
  149. data/firefox/prebuilt/nsINativeEvents.xpt +0 -0
  150. data/firefox/prebuilt/nsIResponseHandler.xpt +0 -0
  151. data/firefox/src/extension/chrome.manifest +3 -0
  152. data/firefox/src/extension/components/badCertListener.js +294 -0
  153. data/firefox/src/extension/components/context.js +37 -0
  154. data/firefox/src/extension/components/driver-component.js +127 -0
  155. data/firefox/src/extension/components/firefoxDriver.js +810 -0
  156. data/firefox/src/extension/components/json2.js +273 -0
  157. data/firefox/src/extension/components/keytest.html +554 -0
  158. data/firefox/src/extension/components/nsCommandProcessor.js +643 -0
  159. data/firefox/src/extension/components/promptService.js +208 -0
  160. data/firefox/src/extension/components/screenshooter.js +81 -0
  161. data/firefox/src/extension/components/socketListener.js +185 -0
  162. data/firefox/src/extension/components/utils.js +1263 -0
  163. data/firefox/src/extension/components/webLoadingListener.js +57 -0
  164. data/firefox/src/extension/components/webdriverserver.js +106 -0
  165. data/firefox/src/extension/components/wrappedElement.js +683 -0
  166. data/firefox/src/extension/content/fxdriver.xul +30 -0
  167. data/firefox/src/extension/content/server.js +95 -0
  168. data/firefox/src/extension/idl/nsICommandProcessor.idl +38 -0
  169. data/firefox/src/extension/idl/nsIResponseHandler.idl +34 -0
  170. data/firefox/src/extension/install.rdf +29 -0
  171. data/firefox/src/rb/lib/selenium/webdriver/firefox.rb +31 -0
  172. data/firefox/src/rb/lib/selenium/webdriver/firefox/binary.rb +107 -0
  173. data/firefox/src/rb/lib/selenium/webdriver/firefox/bridge.rb +484 -0
  174. data/firefox/src/rb/lib/selenium/webdriver/firefox/extension_connection.rb +90 -0
  175. data/firefox/src/rb/lib/selenium/webdriver/firefox/launcher.rb +155 -0
  176. data/firefox/src/rb/lib/selenium/webdriver/firefox/profile.rb +233 -0
  177. data/firefox/src/rb/lib/selenium/webdriver/firefox/profiles_ini.rb +59 -0
  178. data/firefox/src/rb/lib/selenium/webdriver/firefox/util.rb +23 -0
  179. data/jobbie/prebuilt/Win32/Release/InternetExplorerDriver.dll +0 -0
  180. data/jobbie/prebuilt/x64/Release/InternetExplorerDriver.dll +0 -0
  181. data/jobbie/src/rb/lib/selenium/webdriver/ie.rb +14 -0
  182. data/jobbie/src/rb/lib/selenium/webdriver/ie/bridge.rb +565 -0
  183. data/jobbie/src/rb/lib/selenium/webdriver/ie/lib.rb +99 -0
  184. data/jobbie/src/rb/lib/selenium/webdriver/ie/util.rb +147 -0
  185. data/remote/client/src/rb/lib/selenium/webdriver/remote.rb +16 -0
  186. data/remote/client/src/rb/lib/selenium/webdriver/remote/bridge.rb +408 -0
  187. data/remote/client/src/rb/lib/selenium/webdriver/remote/capabilities.rb +105 -0
  188. data/remote/client/src/rb/lib/selenium/webdriver/remote/commands.rb +53 -0
  189. data/remote/client/src/rb/lib/selenium/webdriver/remote/default_http_client.rb +71 -0
  190. data/remote/client/src/rb/lib/selenium/webdriver/remote/response.rb +49 -0
  191. data/remote/client/src/rb/lib/selenium/webdriver/remote/server_error.rb +32 -0
  192. metadata +303 -0
@@ -0,0 +1,72 @@
1
+ <script language="JavaScript">
2
+ if (window["selenium_has_been_loaded_into_this_window"]==null)
3
+ {
4
+
5
+ __SELENIUM_JS__
6
+ // Some background on the code below: broadly speaking, where we are relative to other windows
7
+ // when running in proxy injection mode depends on whether we are in a frame set file or not.
8
+ //
9
+ // In regular HTML files, the selenium JavaScript is injected into an iframe called "selenium"
10
+ // in order to reduce its impact on the JavaScript environment (through namespace pollution,
11
+ // etc.). So in regular HTML files, we need to look at the parent of the current window when we want
12
+ // a handle to, e.g., the application window.
13
+ //
14
+ // In frame set files, we can't use an iframe, so we put the JavaScript in the head element and share
15
+ // the window with the frame set. So in this case, we need to look at the current window, not the
16
+ // parent when looking for, e.g., the application window. (TODO: Perhaps I should have just
17
+ // assigned a regular frame for selenium?)
18
+ //
19
+ BrowserBot.prototype.getContentWindow = function() {
20
+ return window;
21
+ };
22
+
23
+ BrowserBot.prototype.getTargetWindow = function(windowName) {
24
+ return window;
25
+ };
26
+
27
+ BrowserBot.prototype.getCurrentWindow = function() {
28
+ return window;
29
+ };
30
+
31
+ LOG.openLogWindow = function(message, className) {
32
+ // disable for now
33
+ };
34
+
35
+ BrowserBot.prototype.relayToRC = function(name) {
36
+ var object = eval(name);
37
+ var s = 'state:' + serializeObject(name, object) + "\n";
38
+ sendToRC(s,"state=true");
39
+ }
40
+
41
+ function selenium_frameRunTest(oldOnLoadRoutine) {
42
+ if (oldOnLoadRoutine) {
43
+ eval(oldOnLoadRoutine);
44
+ }
45
+ runSeleniumTest();
46
+ }
47
+
48
+ function seleniumOnLoad() {
49
+ injectedSessionId = "@SESSION_ID@";
50
+ window["selenium_has_been_loaded_into_this_window"] = true;
51
+ runSeleniumTest();
52
+ }
53
+
54
+ function seleniumOnUnload() {
55
+ sendToRC("Current window or frame is closed!", "closing=true");
56
+ }
57
+
58
+ if (window.addEventListener) {
59
+ window.addEventListener("load", seleniumOnLoad, false); // firefox
60
+ window.addEventListener("unload", seleniumOnUnload, false); // firefox
61
+ } else if (window.attachEvent){
62
+ window.attachEvent("onload", seleniumOnLoad); // IE
63
+ window.attachEvent("onunload", seleniumOnUnload); // IE
64
+ }
65
+ else {
66
+ throw "causing a JavaScript error to tell the world that I did not arrange to be run on load";
67
+ }
68
+
69
+ injectedSessionId = "@SESSION_ID@";
70
+ proxyInjectionMode = true;
71
+ }
72
+ </script>
@@ -0,0 +1,3291 @@
1
+ /*
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 &#064;id attribute. If no match is
41
+ * found, select the first element whose &#064;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 &#064;id attribute.</li>
45
+ *
46
+ * <li><strong>name</strong>=<em>name</em>:
47
+ * Select the first element with the specified &#064;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[&#064;alt='The image alt text']</li>
75
+ * <li>xpath=//table[&#064;id='table1']//tr[4]/td[2]</li>
76
+ * <li>xpath=//a[contains(&#064;href,'#id1')]</li>
77
+ * <li>xpath=//a[contains(&#064;href,'#id1')]/&#064;class</li>
78
+ * <li>xpath=(//table[&#064;class='stylee'])//th[text()='theHeaderText']/../td</li>
79
+ * <li>xpath=//input[&#064;name='name2' and &#064;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
+ *
102
+ * <li><strong>ui</strong>=<em>uiSpecifierString</em>:
103
+ * Locate an element by resolving the UI specifier string to another locator, and evaluating it. See the <a href="http://svn.openqa.org/fisheye/browse/~raw,r=trunk/selenium/trunk/src/main/resources/core/scripts/ui-doc.html">Selenium UI-Element Reference</a> for more details.
104
+ * <ul class="first last simple">
105
+ * <li>ui=loginPages::loginButton()</li>
106
+ * <li>ui=settingsPages::toggle(label=Hide Email)</li>
107
+ * <li>ui=forumPages::postBody(index=2)//a[2]</li>
108
+ * </ul>
109
+ * </li>
110
+ *
111
+ * </ul>
112
+ *
113
+ * <p>
114
+ * Without an explicit locator prefix, Selenium uses the following default
115
+ * strategies:
116
+ * </p>
117
+ *
118
+ * <ul class="simple">
119
+ * <li><strong>dom</strong>, for locators starting with &quot;document.&quot;</li>
120
+ * <li><strong>xpath</strong>, for locators starting with &quot;//&quot;</li>
121
+ * <li><strong>identifier</strong>, otherwise</li>
122
+ * </ul>
123
+ *
124
+ * <h3><a name="element-filters">Element Filters</a></h3>
125
+ * <blockquote>
126
+ * <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>
127
+ * <p>Filters look much like locators, ie.</p>
128
+ * <blockquote>
129
+ * <em>filterType</em><strong>=</strong><em>argument</em></blockquote>
130
+ *
131
+ * <p>Supported element-filters are:</p>
132
+ * <p><strong>value=</strong><em>valuePattern</em></p>
133
+ * <blockquote>
134
+ * Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons.</blockquote>
135
+ * <p><strong>index=</strong><em>index</em></p>
136
+ * <blockquote>
137
+ * Selects a single element based on its position in the list (offset from zero).</blockquote>
138
+ * </blockquote>
139
+ *
140
+ * <h3><a name="patterns"></a>String-match Patterns</h3>
141
+ *
142
+ * <p>
143
+ * Various Pattern syntaxes are available for matching string values:
144
+ * </p>
145
+ * <ul>
146
+ * <li><strong>glob:</strong><em>pattern</em>:
147
+ * Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a
148
+ * kind of limited regular-expression syntax typically used in command-line
149
+ * shells. In a glob pattern, "*" represents any sequence of characters, and "?"
150
+ * represents any single character. Glob patterns match against the entire
151
+ * string.</li>
152
+ * <li><strong>regexp:</strong><em>regexp</em>:
153
+ * Match a string using a regular-expression. The full power of JavaScript
154
+ * regular-expressions is available.</li>
155
+ * <li><strong>regexpi:</strong><em>regexpi</em>:
156
+ * Match a string using a case-insensitive regular-expression.</li>
157
+ * <li><strong>exact:</strong><em>string</em>:
158
+ *
159
+ * Match a string exactly, verbatim, without any of that fancy wildcard
160
+ * stuff.</li>
161
+ * </ul>
162
+ * <p>
163
+ * If no pattern prefix is specified, Selenium assumes that it's a "glob"
164
+ * pattern.
165
+ * </p>
166
+ * <p>
167
+ * For commands that return multiple values (such as verifySelectOptions),
168
+ * the string being matched is a comma-separated list of the return values,
169
+ * where both commas and backslashes in the values are backslash-escaped.
170
+ * When providing a pattern, the optional matching syntax (i.e. glob,
171
+ * regexp, etc.) is specified once, as usual, at the beginning of the
172
+ * pattern.
173
+ * </p>
174
+ */
175
+ this.browserbot = browserbot;
176
+ this.optionLocatorFactory = new OptionLocatorFactory();
177
+ // DGF for backwards compatibility
178
+ this.page = function() {
179
+ return browserbot;
180
+ };
181
+ this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
182
+ this.mouseSpeed = Selenium.DEFAULT_MOUSE_SPEED;
183
+ }
184
+
185
+ Selenium.DEFAULT_TIMEOUT = 30 * 1000;
186
+ Selenium.DEFAULT_MOUSE_SPEED = 10;
187
+ Selenium.RIGHT_MOUSE_CLICK = 2;
188
+
189
+ Selenium.decorateFunctionWithTimeout = function(f, timeout, callback) {
190
+ if (f == null) {
191
+ return null;
192
+ }
193
+
194
+ var timeoutTime = getTimeoutTime(timeout);
195
+
196
+ return function() {
197
+ if (new Date().getTime() > timeoutTime) {
198
+ if (callback != null) {
199
+ callback();
200
+ }
201
+ throw new SeleniumError("Timed out after " + timeout + "ms");
202
+ }
203
+ return f();
204
+ };
205
+ }
206
+
207
+ Selenium.createForWindow = function(window, proxyInjectionMode) {
208
+ if (!window.location) {
209
+ throw "error: not a window!";
210
+ }
211
+ return new Selenium(BrowserBot.createForWindow(window, proxyInjectionMode));
212
+ };
213
+
214
+ Selenium.prototype.reset = function() {
215
+ this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;
216
+ // todo: this.browserbot.reset()
217
+ this.browserbot.selectWindow("null");
218
+ this.browserbot.resetPopups();
219
+ };
220
+
221
+ Selenium.prototype.doClick = function(locator) {
222
+ /**
223
+ * Clicks on a link, button, checkbox or radio button. If the click action
224
+ * causes a new page to load (like a link usually does), call
225
+ * waitForPageToLoad.
226
+ *
227
+ * @param locator an element locator
228
+ *
229
+ */
230
+ var element = this.browserbot.findElement(locator);
231
+ var elementWithHref = getAncestorOrSelfWithJavascriptHref(element);
232
+
233
+ if (browserVersion.isChrome && elementWithHref != null) {
234
+ // SEL-621: Firefox chrome: Race condition bug in alert-handling code
235
+ //
236
+ // This appears to be because javascript href's are being executed in a
237
+ // separate thread from the main thread when running in chrome mode.
238
+ //
239
+ // This workaround injects a callback into the executing href that
240
+ // lowers a flag, which is initially raised. Execution of this click
241
+ // command will wait for the flag to be lowered.
242
+
243
+ var win = elementWithHref.ownerDocument.defaultView;
244
+ var originalLocation = win.location.href.replace(/#.*/,"");
245
+ var originalHref = elementWithHref.href;
246
+
247
+ var newHref = 'javascript:try { '
248
+ + originalHref.replace(/^\s*javascript:/i, "")
249
+ + ' } finally { window._executingJavascriptHref = undefined; }' ;
250
+ elementWithHref.href = newHref;
251
+
252
+ win._executingJavascriptHref = true;
253
+
254
+ var savedEvent = null;
255
+ var evtListener = function(evt) {
256
+ savedEvent = evt;
257
+ };
258
+
259
+ element.addEventListener("click", evtListener, false);
260
+
261
+ this.browserbot.clickElement(element);
262
+
263
+ element.removeEventListener("click", evtListener, false);
264
+
265
+ // We're relying on javascript that's owned by
266
+ // elementWithHref getting executed. It might not
267
+ // get executed if:
268
+ // 1) the click event was cancelled
269
+ // 2) the page changed the href value on us
270
+ // 3) the elementWithHref was removed from the document
271
+
272
+ if (savedEvent && savedEvent.getPreventDefault()) {
273
+ // click was canceled by event listener
274
+ win._executingJavascriptHref = undefined;
275
+ } else if (elementWithHref.href != newHref) {
276
+ // the page changed the href value on us
277
+ win._executingJavascriptHref = undefined;
278
+ } else {
279
+ // check that elementWithHref is still in the document
280
+ var d = elementWithHref.ownerDocument;
281
+ var html = d ? d.documentElement : null;
282
+ var curElem = elementWithHref;
283
+ while (curElem && html && !curElem.isSameNode(html)) {
284
+ curElem = curElem.parentNode;
285
+ }
286
+ if (!html || !curElem) {
287
+ win._executingJavascriptHref = undefined;
288
+ }
289
+ }
290
+
291
+ return Selenium.decorateFunctionWithTimeout(function() {
292
+ if (win.closed) {
293
+ return true;
294
+ }
295
+ if (win.location.href.replace(/#.*/,"") != originalLocation) {
296
+ // navigated to some other page ... javascript from previous
297
+ // page can't still be executing!
298
+ return true;
299
+ }
300
+ if (! win._executingJavascriptHref) {
301
+ try {
302
+ elementWithHref.href = originalHref;
303
+ }
304
+ catch (e) {
305
+ // maybe the javascript removed the element ... should be
306
+ // no danger in not reverting its href attribute
307
+ }
308
+ return true;
309
+ }
310
+
311
+ return false;
312
+ }, this.defaultTimeout);
313
+ }
314
+
315
+ this.browserbot.clickElement(element);
316
+ };
317
+
318
+ Selenium.prototype.doDoubleClick = function(locator) {
319
+ /**
320
+ * Double clicks on a link, button, checkbox or radio button. If the double click action
321
+ * causes a new page to load (like a link usually does), call
322
+ * waitForPageToLoad.
323
+ *
324
+ * @param locator an element locator
325
+ *
326
+ */
327
+ var element = this.browserbot.findElement(locator);
328
+ this.browserbot.doubleClickElement(element);
329
+ };
330
+
331
+ Selenium.prototype.doContextMenu = function(locator) {
332
+ /**
333
+ * Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element).
334
+ *
335
+ * @param locator an element locator
336
+ *
337
+ */
338
+ var element = this.browserbot.findElement(locator);
339
+ this.browserbot.contextMenuOnElement(element);
340
+ };
341
+
342
+ Selenium.prototype.doClickAt = function(locator, coordString) {
343
+ /**
344
+ * Clicks on a link, button, checkbox or radio button. If the click action
345
+ * causes a new page to load (like a link usually does), call
346
+ * waitForPageToLoad.
347
+ *
348
+ * @param locator an element locator
349
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
350
+ * event relative to the element returned by the locator.
351
+ *
352
+ */
353
+ var element = this.browserbot.findElement(locator);
354
+ var clientXY = getClientXY(element, coordString)
355
+ this.doMouseMove(locator);
356
+ this.doMouseDown(locator);
357
+ this.browserbot.clickElement(element, clientXY[0], clientXY[1]);
358
+ this.doMouseUp(locator);
359
+ };
360
+
361
+ Selenium.prototype.doDoubleClickAt = function(locator, coordString) {
362
+ /**
363
+ * Doubleclicks on a link, button, checkbox or radio button. If the action
364
+ * causes a new page to load (like a link usually does), call
365
+ * waitForPageToLoad.
366
+ *
367
+ * @param locator an element locator
368
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
369
+ * event relative to the element returned by the locator.
370
+ *
371
+ */
372
+ var element = this.browserbot.findElement(locator);
373
+ var clientXY = getClientXY(element, coordString)
374
+ this.doMouseMove(locator);
375
+ this.doMouseDown(locator);
376
+ this.browserbot.doubleClickElement(element, clientXY[0], clientXY[1]);
377
+ this.doMouseUp(locator);
378
+ };
379
+
380
+ Selenium.prototype.doContextMenuAt = function(locator, coordString) {
381
+ /**
382
+ * Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element).
383
+ *
384
+ * @param locator an element locator
385
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
386
+ * event relative to the element returned by the locator.
387
+ *
388
+ */
389
+ var element = this.browserbot.findElement(locator);
390
+ var clientXY = getClientXY(element, coordString)
391
+ this.browserbot.contextMenuOnElement(element, clientXY[0], clientXY[1]);
392
+ };
393
+
394
+ Selenium.prototype.doFireEvent = function(locator, eventName) {
395
+ /**
396
+ * Explicitly simulate an event, to trigger the corresponding &quot;on<em>event</em>&quot;
397
+ * handler.
398
+ *
399
+ * @param locator an <a href="#locators">element locator</a>
400
+ * @param eventName the event name, e.g. "focus" or "blur"
401
+ */
402
+ var element = this.browserbot.findElement(locator);
403
+ triggerEvent(element, eventName, false);
404
+ };
405
+
406
+ Selenium.prototype.doFocus = function(locator) {
407
+ /** Move the focus to the specified element; for example, if the element is an input field, move the cursor to that field.
408
+ *
409
+ * @param locator an <a href="#locators">element locator</a>
410
+ */
411
+ var element = this.browserbot.findElement(locator);
412
+ if (element.focus) {
413
+ element.focus();
414
+ } else {
415
+ triggerEvent(element, "focus", false);
416
+ }
417
+ }
418
+
419
+ Selenium.prototype.doKeyPress = function(locator, keySequence) {
420
+ /**
421
+ * Simulates a user pressing and releasing a key.
422
+ *
423
+ * @param locator an <a href="#locators">element locator</a>
424
+ * @param keySequence Either be a string("\" followed by the numeric keycode
425
+ * of the key to be pressed, normally the ASCII value of that key), or a single
426
+ * character. For example: "w", "\119".
427
+ */
428
+ var element = this.browserbot.findElement(locator);
429
+ triggerKeyEvent(element, 'keypress', keySequence, true,
430
+ this.browserbot.controlKeyDown,
431
+ this.browserbot.altKeyDown,
432
+ this.browserbot.shiftKeyDown,
433
+ this.browserbot.metaKeyDown);
434
+ };
435
+
436
+ Selenium.prototype.doShiftKeyDown = function() {
437
+ /**
438
+ * Press the shift key and hold it down until doShiftUp() is called or a new page is loaded.
439
+ *
440
+ */
441
+ this.browserbot.shiftKeyDown = true;
442
+ };
443
+
444
+ Selenium.prototype.doShiftKeyUp = function() {
445
+ /**
446
+ * Release the shift key.
447
+ *
448
+ */
449
+ this.browserbot.shiftKeyDown = false;
450
+ };
451
+
452
+ Selenium.prototype.doMetaKeyDown = function() {
453
+ /**
454
+ * Press the meta key and hold it down until doMetaUp() is called or a new page is loaded.
455
+ *
456
+ */
457
+ this.browserbot.metaKeyDown = true;
458
+ };
459
+
460
+ Selenium.prototype.doMetaKeyUp = function() {
461
+ /**
462
+ * Release the meta key.
463
+ *
464
+ */
465
+ this.browserbot.metaKeyDown = false;
466
+ };
467
+
468
+ Selenium.prototype.doAltKeyDown = function() {
469
+ /**
470
+ * Press the alt key and hold it down until doAltUp() is called or a new page is loaded.
471
+ *
472
+ */
473
+ this.browserbot.altKeyDown = true;
474
+ };
475
+
476
+ Selenium.prototype.doAltKeyUp = function() {
477
+ /**
478
+ * Release the alt key.
479
+ *
480
+ */
481
+ this.browserbot.altKeyDown = false;
482
+ };
483
+
484
+ Selenium.prototype.doControlKeyDown = function() {
485
+ /**
486
+ * Press the control key and hold it down until doControlUp() is called or a new page is loaded.
487
+ *
488
+ */
489
+ this.browserbot.controlKeyDown = true;
490
+ };
491
+
492
+ Selenium.prototype.doControlKeyUp = function() {
493
+ /**
494
+ * Release the control key.
495
+ *
496
+ */
497
+ this.browserbot.controlKeyDown = false;
498
+ };
499
+
500
+ Selenium.prototype.doKeyDown = function(locator, keySequence) {
501
+ /**
502
+ * Simulates a user pressing a key (without releasing it yet).
503
+ *
504
+ * @param locator an <a href="#locators">element locator</a>
505
+ * @param keySequence Either be a string("\" followed by the numeric keycode
506
+ * of the key to be pressed, normally the ASCII value of that key), or a single
507
+ * character. For example: "w", "\119".
508
+ */
509
+ var element = this.browserbot.findElement(locator);
510
+ triggerKeyEvent(element, 'keydown', keySequence, true,
511
+ this.browserbot.controlKeyDown,
512
+ this.browserbot.altKeyDown,
513
+ this.browserbot.shiftKeyDown,
514
+ this.browserbot.metaKeyDown);
515
+ };
516
+
517
+ Selenium.prototype.doKeyUp = function(locator, keySequence) {
518
+ /**
519
+ * Simulates a user releasing a key.
520
+ *
521
+ * @param locator an <a href="#locators">element locator</a>
522
+ * @param keySequence Either be a string("\" followed by the numeric keycode
523
+ * of the key to be pressed, normally the ASCII value of that key), or a single
524
+ * character. For example: "w", "\119".
525
+ */
526
+ var element = this.browserbot.findElement(locator);
527
+ triggerKeyEvent(element, 'keyup', keySequence, true,
528
+ this.browserbot.controlKeyDown,
529
+ this.browserbot.altKeyDown,
530
+ this.browserbot.shiftKeyDown,
531
+ this.browserbot.metaKeyDown);
532
+ };
533
+
534
+ function getClientXY(element, coordString) {
535
+ // Parse coordString
536
+ var coords = null;
537
+ var x;
538
+ var y;
539
+ if (coordString) {
540
+ coords = coordString.split(/,/);
541
+ x = Number(coords[0]);
542
+ y = Number(coords[1]);
543
+ }
544
+ else {
545
+ x = y = 0;
546
+ }
547
+
548
+ // Get position of element,
549
+ // Return 2 item array with clientX and clientY
550
+ return [Selenium.prototype.getElementPositionLeft(element) + x, Selenium.prototype.getElementPositionTop(element) + y];
551
+ }
552
+
553
+ Selenium.prototype.doMouseOver = function(locator) {
554
+ /**
555
+ * Simulates a user hovering a mouse over the specified element.
556
+ *
557
+ * @param locator an <a href="#locators">element locator</a>
558
+ */
559
+ var element = this.browserbot.findElement(locator);
560
+ this.browserbot.triggerMouseEvent(element, 'mouseover', true);
561
+ };
562
+
563
+ Selenium.prototype.doMouseOut = function(locator) {
564
+ /**
565
+ * Simulates a user moving the mouse pointer away from the specified element.
566
+ *
567
+ * @param locator an <a href="#locators">element locator</a>
568
+ */
569
+ var element = this.browserbot.findElement(locator);
570
+ this.browserbot.triggerMouseEvent(element, 'mouseout', true);
571
+ };
572
+
573
+ Selenium.prototype.doMouseDown = function(locator) {
574
+ /**
575
+ * Simulates a user pressing the left mouse button (without releasing it yet) on
576
+ * the specified element.
577
+ *
578
+ * @param locator an <a href="#locators">element locator</a>
579
+ */
580
+ var element = this.browserbot.findElement(locator);
581
+ this.browserbot.triggerMouseEvent(element, 'mousedown', true);
582
+ };
583
+
584
+ Selenium.prototype.doMouseDownRight = function(locator) {
585
+ /**
586
+ * Simulates a user pressing the right mouse button (without releasing it yet) on
587
+ * the specified element.
588
+ *
589
+ * @param locator an <a href="#locators">element locator</a>
590
+ */
591
+ var element = this.browserbot.findElement(locator);
592
+ this.browserbot.triggerMouseEvent(element, 'mousedown', true, undefined, undefined, Selenium.RIGHT_MOUSE_CLICK);
593
+ };
594
+
595
+ Selenium.prototype.doMouseDownAt = function(locator, coordString) {
596
+ /**
597
+ * Simulates a user pressing the left mouse button (without releasing it yet) at
598
+ * the specified location.
599
+ *
600
+ * @param locator an <a href="#locators">element locator</a>
601
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
602
+ * event relative to the element returned by the locator.
603
+ */
604
+ var element = this.browserbot.findElement(locator);
605
+ var clientXY = getClientXY(element, coordString)
606
+
607
+ this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientXY[0], clientXY[1]);
608
+ };
609
+
610
+ Selenium.prototype.doMouseDownRightAt = function(locator, coordString) {
611
+ /**
612
+ * Simulates a user pressing the right mouse button (without releasing it yet) at
613
+ * the specified location.
614
+ *
615
+ * @param locator an <a href="#locators">element locator</a>
616
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
617
+ * event relative to the element returned by the locator.
618
+ */
619
+ var element = this.browserbot.findElement(locator);
620
+ var clientXY = getClientXY(element, coordString)
621
+
622
+ this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientXY[0], clientXY[1], Selenium.RIGHT_MOUSE_CLICK);
623
+ };
624
+
625
+ Selenium.prototype.doMouseUp = function(locator) {
626
+ /**
627
+ * Simulates the event that occurs when the user releases the mouse button (i.e., stops
628
+ * holding the button down) on the specified element.
629
+ *
630
+ * @param locator an <a href="#locators">element locator</a>
631
+ */
632
+ var element = this.browserbot.findElement(locator);
633
+ this.browserbot.triggerMouseEvent(element, 'mouseup', true);
634
+ };
635
+
636
+ Selenium.prototype.doMouseUpRight = function(locator) {
637
+ /**
638
+ * Simulates the event that occurs when the user releases the right mouse button (i.e., stops
639
+ * holding the button down) on the specified element.
640
+ *
641
+ * @param locator an <a href="#locators">element locator</a>
642
+ */
643
+ var element = this.browserbot.findElement(locator);
644
+ this.browserbot.triggerMouseEvent(element, 'mouseup', true, undefined, undefined, Selenium.RIGHT_MOUSE_CLICK);
645
+ };
646
+
647
+ Selenium.prototype.doMouseUpAt = function(locator, coordString) {
648
+ /**
649
+ * Simulates the event that occurs when the user releases the mouse button (i.e., stops
650
+ * holding the button down) at the specified location.
651
+ *
652
+ * @param locator an <a href="#locators">element locator</a>
653
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
654
+ * event relative to the element returned by the locator.
655
+ */
656
+ var element = this.browserbot.findElement(locator);
657
+ var clientXY = getClientXY(element, coordString)
658
+
659
+ this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientXY[0], clientXY[1]);
660
+ };
661
+
662
+ Selenium.prototype.doMouseUpRightAt = function(locator, coordString) {
663
+ /**
664
+ * Simulates the event that occurs when the user releases the right mouse button (i.e., stops
665
+ * holding the button down) at the specified location.
666
+ *
667
+ * @param locator an <a href="#locators">element locator</a>
668
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
669
+ * event relative to the element returned by the locator.
670
+ */
671
+ var element = this.browserbot.findElement(locator);
672
+ var clientXY = getClientXY(element, coordString)
673
+
674
+ this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientXY[0], clientXY[1], Selenium.RIGHT_MOUSE_CLICK);
675
+ };
676
+
677
+ Selenium.prototype.doMouseMove = function(locator) {
678
+ /**
679
+ * Simulates a user pressing the mouse button (without releasing it yet) on
680
+ * the specified element.
681
+ *
682
+ * @param locator an <a href="#locators">element locator</a>
683
+ */
684
+ var element = this.browserbot.findElement(locator);
685
+ this.browserbot.triggerMouseEvent(element, 'mousemove', true);
686
+ };
687
+
688
+ Selenium.prototype.doMouseMoveAt = function(locator, coordString) {
689
+ /**
690
+ * Simulates a user pressing the mouse button (without releasing it yet) on
691
+ * the specified element.
692
+ *
693
+ * @param locator an <a href="#locators">element locator</a>
694
+ * @param coordString specifies the x,y position (i.e. - 10,20) of the mouse
695
+ * event relative to the element returned by the locator.
696
+ */
697
+
698
+ var element = this.browserbot.findElement(locator);
699
+ var clientXY = getClientXY(element, coordString)
700
+
701
+ this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientXY[0], clientXY[1]);
702
+ };
703
+
704
+ Selenium.prototype.doType = function(locator, value) {
705
+ /**
706
+ * Sets the value of an input field, as though you typed it in.
707
+ *
708
+ * <p>Can also be used to set the value of combo boxes, check boxes, etc. In these cases,
709
+ * value should be the value of the option selected, not the visible text.</p>
710
+ *
711
+ * @param locator an <a href="#locators">element locator</a>
712
+ * @param value the value to type
713
+ */
714
+ if (this.browserbot.controlKeyDown || this.browserbot.altKeyDown || this.browserbot.metaKeyDown) {
715
+ throw new SeleniumError("type not supported immediately after call to controlKeyDown() or altKeyDown() or metaKeyDown()");
716
+ }
717
+ // TODO fail if it can't be typed into.
718
+ var element = this.browserbot.findElement(locator);
719
+ if (this.browserbot.shiftKeyDown) {
720
+ value = new String(value).toUpperCase();
721
+ }
722
+ this.browserbot.replaceText(element, value);
723
+ };
724
+
725
+ Selenium.prototype.doTypeKeys = function(locator, value) {
726
+ /**
727
+ * Simulates keystroke events on the specified element, as though you typed the value key-by-key.
728
+ *
729
+ * <p>This is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string;
730
+ * this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events.</p>
731
+ *
732
+ * <p>Unlike the simple "type" command, which forces the specified value into the page directly, this command
733
+ * may or may not have any visible effect, even in cases where typing keys would normally have a visible effect.
734
+ * For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in
735
+ * the field.</p>
736
+ * <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
737
+ * send the keystroke events corresponding to what you just typed.</p>
738
+ *
739
+ * @param locator an <a href="#locators">element locator</a>
740
+ * @param value the value to type
741
+ */
742
+ var keys = new String(value).split("");
743
+ for (var i = 0; i < keys.length; i++) {
744
+ var c = keys[i];
745
+ this.doKeyDown(locator, c);
746
+ this.doKeyUp(locator, c);
747
+ this.doKeyPress(locator, c);
748
+ }
749
+ };
750
+
751
+ Selenium.prototype.doSetSpeed = function(value) {
752
+ /**
753
+ * 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.,
754
+ * the delay is 0 milliseconds.
755
+ *
756
+ * @param value the number of milliseconds to pause after operation
757
+ */
758
+ throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
759
+ };
760
+
761
+ Selenium.prototype.getSpeed = function() {
762
+ /**
763
+ * 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.,
764
+ * the delay is 0 milliseconds.
765
+ *
766
+ * See also setSpeed.
767
+ *
768
+ * @return string the execution speed in milliseconds.
769
+ */
770
+ throw new SeleniumError("this operation is only implemented in selenium-rc, and should never result in a request making it across the wire");
771
+ };
772
+
773
+ Selenium.prototype.findToggleButton = function(locator) {
774
+ var element = this.browserbot.findElement(locator);
775
+ if (element.checked == null) {
776
+ Assert.fail("Element " + locator + " is not a toggle-button.");
777
+ }
778
+ return element;
779
+ }
780
+
781
+ Selenium.prototype.doCheck = function(locator) {
782
+ /**
783
+ * Check a toggle-button (checkbox/radio)
784
+ *
785
+ * @param locator an <a href="#locators">element locator</a>
786
+ */
787
+ this.findToggleButton(locator).checked = true;
788
+ };
789
+
790
+ Selenium.prototype.doUncheck = function(locator) {
791
+ /**
792
+ * Uncheck a toggle-button (checkbox/radio)
793
+ *
794
+ * @param locator an <a href="#locators">element locator</a>
795
+ */
796
+ this.findToggleButton(locator).checked = false;
797
+ };
798
+
799
+ Selenium.prototype.doSelect = function(selectLocator, optionLocator) {
800
+ /**
801
+ * Select an option from a drop-down using an option locator.
802
+ *
803
+ * <p>
804
+ * Option locators provide different ways of specifying options of an HTML
805
+ * Select element (e.g. for selecting a specific option, or for asserting
806
+ * that the selected option satisfies a specification). There are several
807
+ * forms of Select Option Locator.
808
+ * </p>
809
+ * <ul>
810
+ * <li><strong>label</strong>=<em>labelPattern</em>:
811
+ * matches options based on their labels, i.e. the visible text. (This
812
+ * is the default.)
813
+ * <ul class="first last simple">
814
+ * <li>label=regexp:^[Oo]ther</li>
815
+ * </ul>
816
+ * </li>
817
+ * <li><strong>value</strong>=<em>valuePattern</em>:
818
+ * matches options based on their values.
819
+ * <ul class="first last simple">
820
+ * <li>value=other</li>
821
+ * </ul>
822
+ *
823
+ *
824
+ * </li>
825
+ * <li><strong>id</strong>=<em>id</em>:
826
+ *
827
+ * matches options based on their ids.
828
+ * <ul class="first last simple">
829
+ * <li>id=option1</li>
830
+ * </ul>
831
+ * </li>
832
+ * <li><strong>index</strong>=<em>index</em>:
833
+ * matches an option based on its index (offset from zero).
834
+ * <ul class="first last simple">
835
+ *
836
+ * <li>index=2</li>
837
+ * </ul>
838
+ * </li>
839
+ * </ul>
840
+ * <p>
841
+ * If no option locator prefix is provided, the default behaviour is to match on <strong>label</strong>.
842
+ * </p>
843
+ *
844
+ *
845
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
846
+ * @param optionLocator an option locator (a label by default)
847
+ */
848
+ var element = this.browserbot.findElement(selectLocator);
849
+ if (!("options" in element)) {
850
+ throw new SeleniumError("Specified element is not a Select (has no options)");
851
+ }
852
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
853
+ var option = locator.findOption(element);
854
+ this.browserbot.selectOption(element, option);
855
+ };
856
+
857
+
858
+
859
+ Selenium.prototype.doAddSelection = function(locator, optionLocator) {
860
+ /**
861
+ * Add a selection to the set of selected options in a multi-select element using an option locator.
862
+ *
863
+ * @see #doSelect for details of option locators
864
+ *
865
+ * @param locator an <a href="#locators">element locator</a> identifying a multi-select box
866
+ * @param optionLocator an option locator (a label by default)
867
+ */
868
+ var element = this.browserbot.findElement(locator);
869
+ if (!("options" in element)) {
870
+ throw new SeleniumError("Specified element is not a Select (has no options)");
871
+ }
872
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
873
+ var option = locator.findOption(element);
874
+ this.browserbot.addSelection(element, option);
875
+ };
876
+
877
+ Selenium.prototype.doRemoveSelection = function(locator, optionLocator) {
878
+ /**
879
+ * Remove a selection from the set of selected options in a multi-select element using an option locator.
880
+ *
881
+ * @see #doSelect for details of option locators
882
+ *
883
+ * @param locator an <a href="#locators">element locator</a> identifying a multi-select box
884
+ * @param optionLocator an option locator (a label by default)
885
+ */
886
+
887
+ var element = this.browserbot.findElement(locator);
888
+ if (!("options" in element)) {
889
+ throw new SeleniumError("Specified element is not a Select (has no options)");
890
+ }
891
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
892
+ var option = locator.findOption(element);
893
+ this.browserbot.removeSelection(element, option);
894
+ };
895
+
896
+ Selenium.prototype.doRemoveAllSelections = function(locator) {
897
+ /**
898
+ * Unselects all of the selected options in a multi-select element.
899
+ *
900
+ * @param locator an <a href="#locators">element locator</a> identifying a multi-select box
901
+ */
902
+ var element = this.browserbot.findElement(locator);
903
+ if (!("options" in element)) {
904
+ throw new SeleniumError("Specified element is not a Select (has no options)");
905
+ }
906
+ for (var i = 0; i < element.options.length; i++) {
907
+ this.browserbot.removeSelection(element, element.options[i]);
908
+ }
909
+ }
910
+
911
+ Selenium.prototype.doSubmit = function(formLocator) {
912
+ /**
913
+ * Submit the specified form. This is particularly useful for forms without
914
+ * submit buttons, e.g. single-input "Search" forms.
915
+ *
916
+ * @param formLocator an <a href="#locators">element locator</a> for the form you want to submit
917
+ */
918
+ var form = this.browserbot.findElement(formLocator);
919
+ return this.browserbot.submit(form);
920
+
921
+ };
922
+
923
+ Selenium.prototype.makePageLoadCondition = function(timeout) {
924
+ if (timeout == null) {
925
+ timeout = this.defaultTimeout;
926
+ }
927
+ // if the timeout is zero, we won't wait for the page to load before returning
928
+ if (timeout == 0) {
929
+ // abort XHR request
930
+ this._abortXhrRequest();
931
+ return;
932
+ }
933
+ return Selenium.decorateFunctionWithTimeout(fnBind(this._isNewPageLoaded, this), timeout, fnBind(this._abortXhrRequest, this));
934
+ };
935
+
936
+ Selenium.prototype.doOpen = function(url, ignoreResponseCode) {
937
+ /**
938
+ * Opens an URL in the test frame. This accepts both relative and absolute
939
+ * URLs.
940
+ *
941
+ * The &quot;open&quot; command waits for the page to load before proceeding,
942
+ * ie. the &quot;AndWait&quot; suffix is implicit.
943
+ *
944
+ * <em>Note</em>: The URL must be on the same domain as the runner HTML
945
+ * due to security restrictions in the browser (Same Origin Policy). If you
946
+ * need to open an URL on another domain, use the Selenium Server to start a
947
+ * new browser session on that domain.
948
+ *
949
+ * @param url the URL to open; may be relative or absolute
950
+ * @param ignoreResponseCode (optional) turn off ajax head request functionality
951
+ *
952
+ */
953
+ if (ignoreResponseCode == null) {
954
+ this.browserbot.ignoreResponseCode = false;
955
+ } else if (ignoreResponseCode.toLowerCase() == "true") {
956
+ this.browserbot.ignoreResponseCode = true;
957
+ } else {
958
+ this.browserbot.ignoreResponseCode = false;
959
+ }
960
+ this.browserbot.openLocation(url);
961
+ if (window["proxyInjectionMode"] == null || !window["proxyInjectionMode"]) {
962
+ return this.makePageLoadCondition();
963
+ } // in PI mode, just return "OK"; the server will waitForLoad
964
+ };
965
+
966
+ Selenium.prototype.doOpenWindow = function(url, windowID) {
967
+ /**
968
+ * Opens a popup window (if a window with that ID isn't already open).
969
+ * After opening the window, you'll need to select it using the selectWindow
970
+ * command.
971
+ *
972
+ * <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).
973
+ * In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using
974
+ * an empty (blank) url, like this: openWindow("", "myFunnyWindow").</p>
975
+ *
976
+ * @param url the URL to open, which can be blank
977
+ * @param windowID the JavaScript window ID of the window to select
978
+ */
979
+ this.browserbot.openWindow(url, windowID);
980
+ };
981
+
982
+ Selenium.prototype.doSelectWindow = function(windowID) {
983
+ /**
984
+ * Selects a popup window using a window locator; once a popup window has been selected, all
985
+ * commands go to that window. To select the main window again, use null
986
+ * as the target.
987
+ *
988
+ * <p>
989
+ *
990
+ * Window locators provide different ways of specifying the window object:
991
+ * by title, by internal JavaScript "name," or by JavaScript variable.
992
+ * </p>
993
+ * <ul>
994
+ * <li><strong>title</strong>=<em>My Special Window</em>:
995
+ * Finds the window using the text that appears in the title bar. Be careful;
996
+ * two windows can share the same title. If that happens, this locator will
997
+ * just pick one.
998
+ * </li>
999
+ * <li><strong>name</strong>=<em>myWindow</em>:
1000
+ * Finds the window using its internal JavaScript "name" property. This is the second
1001
+ * parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures, replaceFlag)
1002
+ * (which Selenium intercepts).
1003
+ * </li>
1004
+ * <li><strong>var</strong>=<em>variableName</em>:
1005
+ * Some pop-up windows are unnamed (anonymous), but are associated with a JavaScript variable name in the current
1006
+ * application window, e.g. "window.foo = window.open(url);". In those cases, you can open the window using
1007
+ * "var=foo".
1008
+ * </li>
1009
+ * </ul>
1010
+ * <p>
1011
+ * If no window locator prefix is provided, we'll try to guess what you mean like this:</p>
1012
+ * <p>1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window instantiated by the browser).</p>
1013
+ * <p>2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window, then it is assumed
1014
+ * that this variable contains the return value from a call to the JavaScript window.open() method.</p>
1015
+ * <p>3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names".</p>
1016
+ * <p>4.) If <em>that</em> fails, we'll try looping over all of the known windows to try to find the appropriate "title".
1017
+ * Since "title" is not necessarily unique, this may have unexpected behavior.</p>
1018
+ *
1019
+ * <p>If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log messages
1020
+ * which identify the names of windows created via window.open (and therefore intercepted by Selenium). You will see messages
1021
+ * like the following for each window as it is opened:</p>
1022
+ *
1023
+ * <p><code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"</code></p>
1024
+ *
1025
+ * <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).
1026
+ * (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
1027
+ * an empty (blank) url, like this: openWindow("", "myFunnyWindow").</p>
1028
+ *
1029
+ * @param windowID the JavaScript window ID of the window to select
1030
+ */
1031
+ this.browserbot.selectWindow(windowID);
1032
+ };
1033
+
1034
+ Selenium.prototype.doSelectPopUp = function(windowID) {
1035
+ /**
1036
+ * Simplifies the process of selecting a popup window (and does not offer
1037
+ * functionality beyond what <code>selectWindow()</code> already provides).
1038
+ * <ul>
1039
+ * <li>If <code>windowID</code> is either not specified, or specified as
1040
+ * "null", the first non-top window is selected. The top window is the one
1041
+ * that would be selected by <code>selectWindow()</code> without providing a
1042
+ * <code>windowID</code> . This should not be used when more than one popup
1043
+ * window is in play.</li>
1044
+ * <li>Otherwise, the window will be looked up considering
1045
+ * <code>windowID</code> as the following in order: 1) the "name" of the
1046
+ * window, as specified to <code>window.open()</code>; 2) a javascript
1047
+ * variable which is a reference to a window; and 3) the title of the
1048
+ * window. This is the same ordered lookup performed by
1049
+ * <code>selectWindow</code> .</li>
1050
+ * </ul>
1051
+ *
1052
+ * @param windowID an identifier for the popup window, which can take on a
1053
+ * number of different meanings
1054
+ */
1055
+ this.browserbot.selectPopUp(windowID);
1056
+ };
1057
+
1058
+ Selenium.prototype.doDeselectPopUp = function() {
1059
+ /**
1060
+ * Selects the main window. Functionally equivalent to using
1061
+ * <code>selectWindow()</code> and specifying no value for
1062
+ * <code>windowID</code>.
1063
+ */
1064
+ this.browserbot.selectWindow();
1065
+ }
1066
+
1067
+ Selenium.prototype.doSelectFrame = function(locator) {
1068
+ /**
1069
+ * Selects a frame within the current window. (You may invoke this command
1070
+ * multiple times to select nested frames.) To select the parent frame, use
1071
+ * "relative=parent" as a locator; to select the top frame, use "relative=top".
1072
+ * You can also select a frame by its 0-based index number; select the first frame with
1073
+ * "index=0", or the third frame with "index=2".
1074
+ *
1075
+ * <p>You may also use a DOM expression to identify the frame you want directly,
1076
+ * like this: <code>dom=frames["main"].frames["subframe"]</code></p>
1077
+ *
1078
+ * @param locator an <a href="#locators">element locator</a> identifying a frame or iframe
1079
+ */
1080
+ this.browserbot.selectFrame(locator);
1081
+ };
1082
+
1083
+ Selenium.prototype.getWhetherThisFrameMatchFrameExpression = function(currentFrameString, target) {
1084
+ /**
1085
+ * Determine whether current/locator identify the frame containing this running code.
1086
+ *
1087
+ * <p>This is useful in proxy injection mode, where this code runs in every
1088
+ * browser frame and window, and sometimes the selenium server needs to identify
1089
+ * the "current" frame. In this case, when the test calls selectFrame, this
1090
+ * routine is called for each frame to figure out which one has been selected.
1091
+ * The selected frame will return true, while all others will return false.</p>
1092
+ *
1093
+ * @param currentFrameString starting frame
1094
+ * @param target new frame (which might be relative to the current one)
1095
+ * @return boolean true if the new frame is this code's window
1096
+ */
1097
+ return this.browserbot.doesThisFrameMatchFrameExpression(currentFrameString, target);
1098
+ };
1099
+
1100
+ Selenium.prototype.getWhetherThisWindowMatchWindowExpression = function(currentWindowString, target) {
1101
+ /**
1102
+ * Determine whether currentWindowString plus target identify the window containing this running code.
1103
+ *
1104
+ * <p>This is useful in proxy injection mode, where this code runs in every
1105
+ * browser frame and window, and sometimes the selenium server needs to identify
1106
+ * the "current" window. In this case, when the test calls selectWindow, this
1107
+ * routine is called for each window to figure out which one has been selected.
1108
+ * The selected window will return true, while all others will return false.</p>
1109
+ *
1110
+ * @param currentWindowString starting window
1111
+ * @param target new window (which might be relative to the current one, e.g., "_parent")
1112
+ * @return boolean true if the new window is this code's window
1113
+ */
1114
+ if (window.opener!=null && window.opener[target]!=null && window.opener[target]==window) {
1115
+ return true;
1116
+ }
1117
+ return false;
1118
+ };
1119
+
1120
+ Selenium.prototype.doWaitForPopUp = function(windowID, timeout) {
1121
+ /**
1122
+ * Waits for a popup window to appear and load up.
1123
+ *
1124
+ * @param windowID the JavaScript window "name" of the window that will appear (not the text of the title bar)
1125
+ * If unspecified, or specified as "null", this command will
1126
+ * wait for the first non-top window to appear (don't rely
1127
+ * on this if you are working with multiple popups
1128
+ * simultaneously).
1129
+ * @param timeout a timeout in milliseconds, after which the action will return with an error.
1130
+ * If this value is not specified, the default Selenium
1131
+ * timeout will be used. See the setTimeout() command.
1132
+ */
1133
+ if (! timeout) {
1134
+ var timeout = this.defaultTimeout;
1135
+ }
1136
+ var timeoutTime = getTimeoutTime(timeout);
1137
+
1138
+ var popupLoadedPredicate = function () {
1139
+ var targetWindow;
1140
+ try {
1141
+ if (windowID && windowID != 'null') {
1142
+ targetWindow = selenium.browserbot.getWindowByName(windowID, true);
1143
+ }
1144
+ else {
1145
+ var names = selenium.browserbot.getNonTopWindowNames();
1146
+ targetWindow = selenium.browserbot.getWindowByName(names[0], true);
1147
+ }
1148
+ }
1149
+ catch (e) {
1150
+ if (new Date().getTime() > timeoutTime) {
1151
+ throw e;
1152
+ }
1153
+ }
1154
+
1155
+ if (!targetWindow) return false;
1156
+ if (!targetWindow.location) return false;
1157
+ if ("about:blank" == targetWindow.location) return false;
1158
+ if (browserVersion.isKonqueror) {
1159
+ if ("/" == targetWindow.location.href) {
1160
+ // apparently Konqueror uses this as the temporary location, instead of about:blank
1161
+ return false;
1162
+ }
1163
+ }
1164
+ if (browserVersion.isSafari) {
1165
+ if(targetWindow.location.href == selenium.browserbot.buttonWindow.location.href) {
1166
+ // Apparently Safari uses this as the temporary location, instead of about:blank
1167
+ // what a world!
1168
+ LOG.debug("DGF what a world!");
1169
+ return false;
1170
+ }
1171
+ }
1172
+ if (!targetWindow.document) return false;
1173
+ if (!selenium.browserbot.getCurrentWindow().document.readyState) {
1174
+ // This is Firefox, with no readyState extension
1175
+ return true;
1176
+ }
1177
+ if ('complete' != targetWindow.document.readyState) return false;
1178
+ return true;
1179
+ };
1180
+
1181
+ return Selenium.decorateFunctionWithTimeout(popupLoadedPredicate, timeout);
1182
+ }
1183
+
1184
+ Selenium.prototype.doWaitForPopUp.dontCheckAlertsAndConfirms = true;
1185
+
1186
+ Selenium.prototype.doChooseCancelOnNextConfirmation = function() {
1187
+ /**
1188
+ * <p>
1189
+ * By default, Selenium's overridden window.confirm() function will
1190
+ * return true, as if the user had manually clicked OK; after running
1191
+ * this command, the next call to confirm() will return false, as if
1192
+ * the user had clicked Cancel. Selenium will then resume using the
1193
+ * default behavior for future confirmations, automatically returning
1194
+ * true (OK) unless/until you explicitly call this command for each
1195
+ * confirmation.
1196
+ * </p>
1197
+ * <p>
1198
+ * Take note - every time a confirmation comes up, you must
1199
+ * consume it with a corresponding getConfirmation, or else
1200
+ * the next selenium operation will fail.
1201
+ * </p>
1202
+ */
1203
+ this.browserbot.cancelNextConfirmation(false);
1204
+ };
1205
+
1206
+ Selenium.prototype.doChooseOkOnNextConfirmation = function() {
1207
+ /**
1208
+ * <p>
1209
+ * Undo the effect of calling chooseCancelOnNextConfirmation. Note
1210
+ * that Selenium's overridden window.confirm() function will normally automatically
1211
+ * return true, as if the user had manually clicked OK, so you shouldn't
1212
+ * need to use this command unless for some reason you need to change
1213
+ * your mind prior to the next confirmation. After any confirmation, Selenium will resume using the
1214
+ * default behavior for future confirmations, automatically returning
1215
+ * true (OK) unless/until you explicitly call chooseCancelOnNextConfirmation for each
1216
+ * confirmation.
1217
+ * </p>
1218
+ * <p>
1219
+ * Take note - every time a confirmation comes up, you must
1220
+ * consume it with a corresponding getConfirmation, or else
1221
+ * the next selenium operation will fail.
1222
+ * </p>
1223
+ *
1224
+ */
1225
+ this.browserbot.cancelNextConfirmation(true);
1226
+ };
1227
+
1228
+ Selenium.prototype.doAnswerOnNextPrompt = function(answer) {
1229
+ /**
1230
+ * Instructs Selenium to return the specified answer string in response to
1231
+ * the next JavaScript prompt [window.prompt()].
1232
+ *
1233
+ *
1234
+ * @param answer the answer to give in response to the prompt pop-up
1235
+ */
1236
+ this.browserbot.setNextPromptResult(answer);
1237
+ };
1238
+
1239
+ Selenium.prototype.doGoBack = function() {
1240
+ /**
1241
+ * Simulates the user clicking the "back" button on their browser.
1242
+ *
1243
+ */
1244
+ this.browserbot.goBack();
1245
+ };
1246
+
1247
+ Selenium.prototype.doRefresh = function() {
1248
+ /**
1249
+ * Simulates the user clicking the "Refresh" button on their browser.
1250
+ *
1251
+ */
1252
+ this.browserbot.refresh();
1253
+ };
1254
+
1255
+ Selenium.prototype.doClose = function() {
1256
+ /**
1257
+ * Simulates the user clicking the "close" button in the titlebar of a popup
1258
+ * window or tab.
1259
+ */
1260
+ this.browserbot.close();
1261
+ };
1262
+
1263
+ Selenium.prototype.ensureNoUnhandledPopups = function() {
1264
+ if (this.browserbot.hasAlerts()) {
1265
+ throw new SeleniumError("There was an unexpected Alert! [" + this.browserbot.getNextAlert() + "]");
1266
+ }
1267
+ if ( this.browserbot.hasConfirmations() ) {
1268
+ throw new SeleniumError("There was an unexpected Confirmation! [" + this.browserbot.getNextConfirmation() + "]");
1269
+ }
1270
+ };
1271
+
1272
+ Selenium.prototype.isAlertPresent = function() {
1273
+ /**
1274
+ * Has an alert occurred?
1275
+ *
1276
+ * <p>
1277
+ * This function never throws an exception
1278
+ * </p>
1279
+ * @return boolean true if there is an alert
1280
+ */
1281
+ return this.browserbot.hasAlerts();
1282
+ };
1283
+
1284
+ Selenium.prototype.isPromptPresent = function() {
1285
+ /**
1286
+ * Has a prompt occurred?
1287
+ *
1288
+ * <p>
1289
+ * This function never throws an exception
1290
+ * </p>
1291
+ * @return boolean true if there is a pending prompt
1292
+ */
1293
+ return this.browserbot.hasPrompts();
1294
+ };
1295
+
1296
+ Selenium.prototype.isConfirmationPresent = function() {
1297
+ /**
1298
+ * Has confirm() been called?
1299
+ *
1300
+ * <p>
1301
+ * This function never throws an exception
1302
+ * </p>
1303
+ * @return boolean true if there is a pending confirmation
1304
+ */
1305
+ return this.browserbot.hasConfirmations();
1306
+ };
1307
+ Selenium.prototype.getAlert = function() {
1308
+ /**
1309
+ * Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.
1310
+ *
1311
+ * <p>Getting an alert has the same effect as manually clicking OK. If an
1312
+ * alert is generated but you do not consume it with getAlert, the next Selenium action
1313
+ * will fail.</p>
1314
+ *
1315
+ * <p>Under Selenium, JavaScript alerts will NOT pop up a visible alert
1316
+ * dialog.</p>
1317
+ *
1318
+ * <p>Selenium does NOT support JavaScript alerts that are generated in a
1319
+ * page's onload() event handler. In this case a visible dialog WILL be
1320
+ * generated and Selenium will hang until someone manually clicks OK.</p>
1321
+ * @return string The message of the most recent JavaScript alert
1322
+
1323
+ */
1324
+ if (!this.browserbot.hasAlerts()) {
1325
+ Assert.fail("There were no alerts");
1326
+ }
1327
+ return this.browserbot.getNextAlert();
1328
+ };
1329
+ Selenium.prototype.getAlert.dontCheckAlertsAndConfirms = true;
1330
+
1331
+ Selenium.prototype.getConfirmation = function() {
1332
+ /**
1333
+ * Retrieves the message of a JavaScript confirmation dialog generated during
1334
+ * the previous action.
1335
+ *
1336
+ * <p>
1337
+ * By default, the confirm function will return true, having the same effect
1338
+ * as manually clicking OK. This can be changed by prior execution of the
1339
+ * chooseCancelOnNextConfirmation command.
1340
+ * </p>
1341
+ * <p>
1342
+ * If an confirmation is generated but you do not consume it with getConfirmation,
1343
+ * the next Selenium action will fail.
1344
+ * </p>
1345
+ *
1346
+ * <p>
1347
+ * NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible
1348
+ * dialog.
1349
+ * </p>
1350
+ *
1351
+ * <p>
1352
+ * NOTE: Selenium does NOT support JavaScript confirmations that are
1353
+ * generated in a page's onload() event handler. In this case a visible
1354
+ * dialog WILL be generated and Selenium will hang until you manually click
1355
+ * OK.
1356
+ * </p>
1357
+ *
1358
+ * @return string the message of the most recent JavaScript confirmation dialog
1359
+ */
1360
+ if (!this.browserbot.hasConfirmations()) {
1361
+ Assert.fail("There were no confirmations");
1362
+ }
1363
+ return this.browserbot.getNextConfirmation();
1364
+ };
1365
+ Selenium.prototype.getConfirmation.dontCheckAlertsAndConfirms = true;
1366
+
1367
+ Selenium.prototype.getPrompt = function() {
1368
+ /**
1369
+ * Retrieves the message of a JavaScript question prompt dialog generated during
1370
+ * the previous action.
1371
+ *
1372
+ * <p>Successful handling of the prompt requires prior execution of the
1373
+ * answerOnNextPrompt command. If a prompt is generated but you
1374
+ * do not get/verify it, the next Selenium action will fail.</p>
1375
+ *
1376
+ * <p>NOTE: under Selenium, JavaScript prompts will NOT pop up a visible
1377
+ * dialog.</p>
1378
+ *
1379
+ * <p>NOTE: Selenium does NOT support JavaScript prompts that are generated in a
1380
+ * page's onload() event handler. In this case a visible dialog WILL be
1381
+ * generated and Selenium will hang until someone manually clicks OK.</p>
1382
+ * @return string the message of the most recent JavaScript question prompt
1383
+ */
1384
+ if (! this.browserbot.hasPrompts()) {
1385
+ Assert.fail("There were no prompts");
1386
+ }
1387
+ return this.browserbot.getNextPrompt();
1388
+ };
1389
+
1390
+ Selenium.prototype.getLocation = function() {
1391
+ /** Gets the absolute URL of the current page.
1392
+ *
1393
+ * @return string the absolute URL of the current page
1394
+ */
1395
+ return this.browserbot.getCurrentWindow().location.href;
1396
+ };
1397
+
1398
+ Selenium.prototype.getTitle = function() {
1399
+ /** Gets the title of the current page.
1400
+ *
1401
+ * @return string the title of the current page
1402
+ */
1403
+ return this.browserbot.getTitle();
1404
+ };
1405
+
1406
+
1407
+ Selenium.prototype.getBodyText = function() {
1408
+ /**
1409
+ * Gets the entire text of the page.
1410
+ * @return string the entire text of the page
1411
+ */
1412
+ return this.browserbot.bodyText();
1413
+ };
1414
+
1415
+
1416
+ Selenium.prototype.getValue = function(locator) {
1417
+ /**
1418
+ * Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter).
1419
+ * For checkbox/radio elements, the value will be "on" or "off" depending on
1420
+ * whether the element is checked or not.
1421
+ *
1422
+ * @param locator an <a href="#locators">element locator</a>
1423
+ * @return string the element value, or "on/off" for checkbox/radio elements
1424
+ */
1425
+ var element = this.browserbot.findElement(locator)
1426
+ return getInputValue(element).trim();
1427
+ }
1428
+
1429
+ Selenium.prototype.getText = function(locator) {
1430
+ /**
1431
+ * Gets the text of an element. This works for any element that contains
1432
+ * text. This command uses either the textContent (Mozilla-like browsers) or
1433
+ * the innerText (IE-like browsers) of the element, which is the rendered
1434
+ * text shown to the user.
1435
+ *
1436
+ * @param locator an <a href="#locators">element locator</a>
1437
+ * @return string the text of the element
1438
+ */
1439
+ var element = this.browserbot.findElement(locator);
1440
+ return getText(element).trim();
1441
+ };
1442
+
1443
+ Selenium.prototype.doHighlight = function(locator) {
1444
+ /**
1445
+ * Briefly changes the backgroundColor of the specified element yellow. Useful for debugging.
1446
+ *
1447
+ * @param locator an <a href="#locators">element locator</a>
1448
+ */
1449
+ var element = this.browserbot.findElement(locator);
1450
+ this.browserbot.highlight(element, true);
1451
+ };
1452
+
1453
+ Selenium.prototype.getEval = function(script) {
1454
+ /** Gets the result of evaluating the specified JavaScript snippet. The snippet may
1455
+ * have multiple lines, but only the result of the last line will be returned.
1456
+ *
1457
+ * <p>Note that, by default, the snippet will run in the context of the "selenium"
1458
+ * object itself, so <code>this</code> will refer to the Selenium object. Use <code>window</code> to
1459
+ * refer to the window of your application, e.g. <code>window.document.getElementById('foo')</code></p>
1460
+ *
1461
+ * <p>If you need to use
1462
+ * a locator to refer to a single element in your application page, you can
1463
+ * use <code>this.browserbot.findElement("id=foo")</code> where "id=foo" is your locator.</p>
1464
+ *
1465
+ * @param script the JavaScript snippet to run
1466
+ * @return string the results of evaluating the snippet
1467
+ */
1468
+ try {
1469
+ var window = this.browserbot.getCurrentWindow();
1470
+ var result = eval(script);
1471
+ // Selenium RC doesn't allow returning null
1472
+ if (null == result) return "null";
1473
+ return result;
1474
+ } catch (e) {
1475
+ throw new SeleniumError("Threw an exception: " + extractExceptionMessage(e));
1476
+ }
1477
+ };
1478
+
1479
+ Selenium.prototype.isChecked = function(locator) {
1480
+ /**
1481
+ * Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button.
1482
+ * @param locator an <a href="#locators">element locator</a> pointing to a checkbox or radio button
1483
+ * @return boolean true if the checkbox is checked, false otherwise
1484
+ */
1485
+ var element = this.browserbot.findElement(locator);
1486
+ if (element.checked == null) {
1487
+ throw new SeleniumError("Element " + locator + " is not a toggle-button.");
1488
+ }
1489
+ return element.checked;
1490
+ };
1491
+
1492
+ Selenium.prototype.getTable = function(tableCellAddress) {
1493
+ /**
1494
+ * Gets the text from a cell of a table. The cellAddress syntax
1495
+ * tableLocator.row.column, where row and column start at 0.
1496
+ *
1497
+ * @param tableCellAddress a cell address, e.g. "foo.1.4"
1498
+ * @return string the text from the specified cell
1499
+ */
1500
+ // This regular expression matches "tableName.row.column"
1501
+ // For example, "mytable.3.4"
1502
+ pattern = /(.*)\.(\d+)\.(\d+)/;
1503
+
1504
+ if(!pattern.test(tableCellAddress)) {
1505
+ throw new SeleniumError("Invalid target format. Correct format is tableName.rowNum.columnNum");
1506
+ }
1507
+
1508
+ pieces = tableCellAddress.match(pattern);
1509
+
1510
+ tableName = pieces[1];
1511
+ row = pieces[2];
1512
+ col = pieces[3];
1513
+
1514
+ var table = this.browserbot.findElement(tableName);
1515
+ if (row > table.rows.length) {
1516
+ Assert.fail("Cannot access row " + row + " - table has " + table.rows.length + " rows");
1517
+ }
1518
+ else if (col > table.rows[row].cells.length) {
1519
+ Assert.fail("Cannot access column " + col + " - table row has " + table.rows[row].cells.length + " columns");
1520
+ }
1521
+ else {
1522
+ actualContent = getText(table.rows[row].cells[col]);
1523
+ return actualContent.trim();
1524
+ }
1525
+ return null;
1526
+ };
1527
+
1528
+ Selenium.prototype.getSelectedLabels = function(selectLocator) {
1529
+ /** Gets all option labels (visible text) for selected options in the specified select or multi-select element.
1530
+ *
1531
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1532
+ * @return string[] an array of all selected option labels in the specified select drop-down
1533
+ */
1534
+ return this.findSelectedOptionProperties(selectLocator, "text");
1535
+ }
1536
+
1537
+ Selenium.prototype.getSelectedLabel = function(selectLocator) {
1538
+ /** Gets option label (visible text) for selected option in the specified select element.
1539
+ *
1540
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1541
+ * @return string the selected option label in the specified select drop-down
1542
+ */
1543
+ return this.findSelectedOptionProperty(selectLocator, "text");
1544
+ }
1545
+
1546
+ Selenium.prototype.getSelectedValues = function(selectLocator) {
1547
+ /** Gets all option values (value attributes) for selected options in the specified select or multi-select element.
1548
+ *
1549
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1550
+ * @return string[] an array of all selected option values in the specified select drop-down
1551
+ */
1552
+ return this.findSelectedOptionProperties(selectLocator, "value");
1553
+ }
1554
+
1555
+ Selenium.prototype.getSelectedValue = function(selectLocator) {
1556
+ /** Gets option value (value attribute) for selected option in the specified select element.
1557
+ *
1558
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1559
+ * @return string the selected option value in the specified select drop-down
1560
+ */
1561
+ return this.findSelectedOptionProperty(selectLocator, "value");
1562
+ }
1563
+
1564
+ Selenium.prototype.getSelectedIndexes = function(selectLocator) {
1565
+ /** Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element.
1566
+ *
1567
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1568
+ * @return string[] an array of all selected option indexes in the specified select drop-down
1569
+ */
1570
+ return this.findSelectedOptionProperties(selectLocator, "index");
1571
+ }
1572
+
1573
+ Selenium.prototype.getSelectedIndex = function(selectLocator) {
1574
+ /** Gets option index (option number, starting at 0) for selected option in the specified select element.
1575
+ *
1576
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1577
+ * @return string the selected option index in the specified select drop-down
1578
+ */
1579
+ return this.findSelectedOptionProperty(selectLocator, "index");
1580
+ }
1581
+
1582
+ Selenium.prototype.getSelectedIds = function(selectLocator) {
1583
+ /** Gets all option element IDs for selected options in the specified select or multi-select element.
1584
+ *
1585
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1586
+ * @return string[] an array of all selected option IDs in the specified select drop-down
1587
+ */
1588
+ return this.findSelectedOptionProperties(selectLocator, "id");
1589
+ }
1590
+
1591
+ Selenium.prototype.getSelectedId = function(selectLocator) {
1592
+ /** Gets option element ID for selected option in the specified select element.
1593
+ *
1594
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1595
+ * @return string the selected option ID in the specified select drop-down
1596
+ */
1597
+ return this.findSelectedOptionProperty(selectLocator, "id");
1598
+ }
1599
+
1600
+ Selenium.prototype.isSomethingSelected = function(selectLocator) {
1601
+ /** Determines whether some option in a drop-down menu is selected.
1602
+ *
1603
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1604
+ * @return boolean true if some option has been selected, false otherwise
1605
+ */
1606
+ var element = this.browserbot.findElement(selectLocator);
1607
+ if (!("options" in element)) {
1608
+ throw new SeleniumError("Specified element is not a Select (has no options)");
1609
+ }
1610
+
1611
+ var selectedOptions = [];
1612
+
1613
+ for (var i = 0; i < element.options.length; i++) {
1614
+ if (element.options[i].selected)
1615
+ {
1616
+ return true;
1617
+ }
1618
+ }
1619
+ return false;
1620
+ }
1621
+
1622
+ Selenium.prototype.findSelectedOptionProperties = function(locator, property) {
1623
+ var element = this.browserbot.findElement(locator);
1624
+ if (!("options" in element)) {
1625
+ throw new SeleniumError("Specified element is not a Select (has no options)");
1626
+ }
1627
+
1628
+ var selectedOptions = [];
1629
+
1630
+ for (var i = 0; i < element.options.length; i++) {
1631
+ if (element.options[i].selected)
1632
+ {
1633
+ var propVal = element.options[i][property];
1634
+ selectedOptions.push(propVal);
1635
+ }
1636
+ }
1637
+ if (selectedOptions.length == 0) Assert.fail("No option selected");
1638
+ return selectedOptions;
1639
+ }
1640
+
1641
+ Selenium.prototype.findSelectedOptionProperty = function(locator, property) {
1642
+ var selectedOptions = this.findSelectedOptionProperties(locator, property);
1643
+ if (selectedOptions.length > 1) {
1644
+ Assert.fail("More than one selected option!");
1645
+ }
1646
+ return selectedOptions[0];
1647
+ }
1648
+
1649
+ Selenium.prototype.getSelectOptions = function(selectLocator) {
1650
+ /** Gets all option labels in the specified select drop-down.
1651
+ *
1652
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
1653
+ * @return string[] an array of all option labels in the specified select drop-down
1654
+ */
1655
+ var element = this.browserbot.findElement(selectLocator);
1656
+
1657
+ var selectOptions = [];
1658
+
1659
+ for (var i = 0; i < element.options.length; i++) {
1660
+ var option = element.options[i].text;
1661
+ selectOptions.push(option);
1662
+ }
1663
+
1664
+ return selectOptions;
1665
+ };
1666
+
1667
+
1668
+ Selenium.prototype.getAttribute = function(attributeLocator) {
1669
+ /**
1670
+ * Gets the value of an element attribute. The value of the attribute may
1671
+ * differ across browsers (this is the case for the "style" attribute, for
1672
+ * example).
1673
+ *
1674
+ * @param attributeLocator an element locator followed by an &#064; sign and then the name of the attribute, e.g. "foo&#064;bar"
1675
+ * @return string the value of the specified attribute
1676
+ */
1677
+ var result = this.browserbot.findAttribute(attributeLocator);
1678
+ if (result == null) {
1679
+ throw new SeleniumError("Could not find element attribute: " + attributeLocator);
1680
+ }
1681
+ return result;
1682
+ };
1683
+
1684
+ Selenium.prototype.isTextPresent = function(pattern) {
1685
+ /**
1686
+ * Verifies that the specified text pattern appears somewhere on the rendered page shown to the user.
1687
+ * @param pattern a <a href="#patterns">pattern</a> to match with the text of the page
1688
+ * @return boolean true if the pattern matches the text, false otherwise
1689
+ */
1690
+ var allText = this.browserbot.bodyText();
1691
+
1692
+ var patternMatcher = new PatternMatcher(pattern);
1693
+ if (patternMatcher.strategy == PatternMatcher.strategies.glob) {
1694
+ if (pattern.indexOf("glob:")==0) {
1695
+ pattern = pattern.substring("glob:".length); // strip off "glob:"
1696
+ }
1697
+ patternMatcher.matcher = new PatternMatcher.strategies.globContains(pattern);
1698
+ }
1699
+ else if (patternMatcher.strategy == PatternMatcher.strategies.exact) {
1700
+ pattern = pattern.substring("exact:".length); // strip off "exact:"
1701
+ return allText.indexOf(pattern) != -1;
1702
+ }
1703
+ return patternMatcher.matches(allText);
1704
+ };
1705
+
1706
+ Selenium.prototype.isElementPresent = function(locator) {
1707
+ /**
1708
+ * Verifies that the specified element is somewhere on the page.
1709
+ * @param locator an <a href="#locators">element locator</a>
1710
+ * @return boolean true if the element is present, false otherwise
1711
+ */
1712
+ var element = this.browserbot.findElementOrNull(locator);
1713
+ if (element == null) {
1714
+ return false;
1715
+ }
1716
+ return true;
1717
+ };
1718
+
1719
+ Selenium.prototype.isVisible = function(locator) {
1720
+ /**
1721
+ * Determines if the specified element is visible. An
1722
+ * element can be rendered invisible by setting the CSS "visibility"
1723
+ * property to "hidden", or the "display" property to "none", either for the
1724
+ * element itself or one if its ancestors. This method will fail if
1725
+ * the element is not present.
1726
+ *
1727
+ * @param locator an <a href="#locators">element locator</a>
1728
+ * @return boolean true if the specified element is visible, false otherwise
1729
+ */
1730
+ var element;
1731
+ element = this.browserbot.findElement(locator);
1732
+ // DGF if it's an input tag of type "hidden" then it's not visible
1733
+ if (element.tagName) {
1734
+ var tagName = new String(element.tagName).toLowerCase();
1735
+ if (tagName == "input") {
1736
+ if (element.type) {
1737
+ var elementType = new String(element.type).toLowerCase();
1738
+ if (elementType == "hidden") {
1739
+ return false;
1740
+ }
1741
+ }
1742
+ }
1743
+ }
1744
+ var visibility = this.findEffectiveStyleProperty(element, "visibility");
1745
+ var _isDisplayed = this._isDisplayed(element);
1746
+ return (visibility != "hidden" && _isDisplayed);
1747
+ };
1748
+
1749
+ Selenium.prototype.findEffectiveStyleProperty = function(element, property) {
1750
+ var effectiveStyle = this.findEffectiveStyle(element);
1751
+ var propertyValue = effectiveStyle[property];
1752
+ if (propertyValue == 'inherit' && element.parentNode.style) {
1753
+ return this.findEffectiveStyleProperty(element.parentNode, property);
1754
+ }
1755
+ return propertyValue;
1756
+ };
1757
+
1758
+ Selenium.prototype._isDisplayed = function(element) {
1759
+ var display = this.findEffectiveStyleProperty(element, "display");
1760
+ if (display == "none") return false;
1761
+ if (element.parentNode.style) {
1762
+ return this._isDisplayed(element.parentNode);
1763
+ }
1764
+ return true;
1765
+ };
1766
+
1767
+ Selenium.prototype.findEffectiveStyle = function(element) {
1768
+ if (element.style == undefined) {
1769
+ return undefined; // not a styled element
1770
+ }
1771
+ var window = this.browserbot.getCurrentWindow();
1772
+ if (window.getComputedStyle) {
1773
+ // DOM-Level-2-CSS
1774
+ return window.getComputedStyle(element, null);
1775
+ }
1776
+ if (element.currentStyle) {
1777
+ // non-standard IE alternative
1778
+ return element.currentStyle;
1779
+ // TODO: this won't really work in a general sense, as
1780
+ // currentStyle is not identical to getComputedStyle()
1781
+ // ... but it's good enough for "visibility"
1782
+ }
1783
+
1784
+ if (window.document.defaultView && window.document.defaultView.getComputedStyle) {
1785
+ return window.document.defaultView.getComputedStyle(element, null);
1786
+ }
1787
+
1788
+
1789
+ throw new SeleniumError("cannot determine effective stylesheet in this browser");
1790
+ };
1791
+
1792
+ Selenium.prototype.isEditable = function(locator) {
1793
+ /**
1794
+ * Determines whether the specified input element is editable, ie hasn't been disabled.
1795
+ * This method will fail if the specified element isn't an input element.
1796
+ *
1797
+ * @param locator an <a href="#locators">element locator</a>
1798
+ * @return boolean true if the input element is editable, false otherwise
1799
+ */
1800
+ var element = this.browserbot.findElement(locator);
1801
+ if (element.value == undefined) {
1802
+ Assert.fail("Element " + locator + " is not an input.");
1803
+ }
1804
+ if (element.disabled) {
1805
+ return false;
1806
+ }
1807
+ // DGF "readonly" is a bit goofy... it doesn't necessarily have a value
1808
+ // You can write <input readonly value="black">
1809
+ var readOnlyNode = element.getAttributeNode('readonly');
1810
+ if (readOnlyNode) {
1811
+ // DGF on IE, every input element has a readOnly node, but it may be false
1812
+ if (typeof(readOnlyNode.nodeValue) == "boolean") {
1813
+ var readOnly = readOnlyNode.nodeValue;
1814
+ if (readOnly) {
1815
+ return false;
1816
+ }
1817
+ } else {
1818
+ return false;
1819
+ }
1820
+ }
1821
+ return true;
1822
+ };
1823
+
1824
+ Selenium.prototype.getAllButtons = function() {
1825
+ /** Returns the IDs of all buttons on the page.
1826
+ *
1827
+ * <p>If a given button has no ID, it will appear as "" in this array.</p>
1828
+ *
1829
+ * @return string[] the IDs of all buttons on the page
1830
+ */
1831
+ return this.browserbot.getAllButtons();
1832
+ };
1833
+
1834
+ Selenium.prototype.getAllLinks = function() {
1835
+ /** Returns the IDs of all links on the page.
1836
+ *
1837
+ * <p>If a given link has no ID, it will appear as "" in this array.</p>
1838
+ *
1839
+ * @return string[] the IDs of all links on the page
1840
+ */
1841
+ return this.browserbot.getAllLinks();
1842
+ };
1843
+
1844
+ Selenium.prototype.getAllFields = function() {
1845
+ /** Returns the IDs of all input fields on the page.
1846
+ *
1847
+ * <p>If a given field has no ID, it will appear as "" in this array.</p>
1848
+ *
1849
+ * @return string[] the IDs of all field on the page
1850
+ */
1851
+ return this.browserbot.getAllFields();
1852
+ };
1853
+
1854
+ Selenium.prototype.getAttributeFromAllWindows = function(attributeName) {
1855
+ /** Returns an array of JavaScript property values from all known windows having one.
1856
+ *
1857
+ * @param attributeName name of an attribute on the windows
1858
+ * @return string[] the set of values of this attribute from all known windows.
1859
+ */
1860
+ var attributes = new Array();
1861
+
1862
+ var win = selenium.browserbot.topWindow;
1863
+
1864
+ // DGF normally you should use []s instead of eval "win."+attributeName
1865
+ // but in this case, attributeName may contain dots (e.g. document.title)
1866
+ // in that case, we have no choice but to use eval...
1867
+ attributes.push(eval("win."+attributeName));
1868
+ for (var windowName in this.browserbot.openedWindows)
1869
+ {
1870
+ try {
1871
+ win = selenium.browserbot.openedWindows[windowName];
1872
+ attributes.push(eval("win."+attributeName));
1873
+ } catch (e) {} // DGF If we miss one... meh. It's probably closed or inaccessible anyway.
1874
+ }
1875
+ return attributes;
1876
+ };
1877
+
1878
+ Selenium.prototype.findWindow = function(soughtAfterWindowPropertyValue) {
1879
+ var targetPropertyName = "name";
1880
+ if (soughtAfterWindowPropertyValue.match("^title=")) {
1881
+ targetPropertyName = "document.title";
1882
+ soughtAfterWindowPropertyValue = soughtAfterWindowPropertyValue.replace(/^title=/, "");
1883
+ }
1884
+ else {
1885
+ // matching "name":
1886
+ // If we are not in proxy injection mode, then the top-level test window will be named selenium_myiframe.
1887
+ // But as far as the interface goes, we are expected to match a blank string to this window, if
1888
+ // we are searching with respect to the widow name.
1889
+ // So make a special case so that this logic will work:
1890
+ if (PatternMatcher.matches(soughtAfterWindowPropertyValue, "")) {
1891
+ return this.browserbot.getCurrentWindow();
1892
+ }
1893
+ }
1894
+
1895
+ // DGF normally you should use []s instead of eval "win."+attributeName
1896
+ // but in this case, attributeName may contain dots (e.g. document.title)
1897
+ // in that case, we have no choice but to use eval...
1898
+ if (PatternMatcher.matches(soughtAfterWindowPropertyValue, eval("this.browserbot.topWindow." + targetPropertyName))) {
1899
+ return this.browserbot.topWindow;
1900
+ }
1901
+ for (windowName in selenium.browserbot.openedWindows) {
1902
+ var openedWindow = selenium.browserbot.openedWindows[windowName];
1903
+ if (PatternMatcher.matches(soughtAfterWindowPropertyValue, eval("openedWindow." + targetPropertyName))) {
1904
+ return openedWindow;
1905
+ }
1906
+ }
1907
+ throw new SeleniumError("could not find window with property " + targetPropertyName + " matching " + soughtAfterWindowPropertyValue);
1908
+ };
1909
+
1910
+ Selenium.prototype.doDragdrop = function(locator, movementsString) {
1911
+ /** deprecated - use dragAndDrop instead
1912
+ *
1913
+ * @param locator an element locator
1914
+ * @param movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
1915
+ */
1916
+ this.doDragAndDrop(locator, movementsString);
1917
+ };
1918
+
1919
+ Selenium.prototype.doSetMouseSpeed = function(pixels) {
1920
+ /** Configure the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
1921
+ * <p>Setting this value to 0 means that we'll send a "mousemove" event to every single pixel
1922
+ * in between the start location and the end location; that can be very slow, and may
1923
+ * cause some browsers to force the JavaScript to timeout.</p>
1924
+ *
1925
+ * <p>If the mouse speed is greater than the distance between the two dragged objects, we'll
1926
+ * just send one "mousemove" at the start location and then one final one at the end location.</p>
1927
+ * @param pixels the number of pixels between "mousemove" events
1928
+ */
1929
+ var intValue = new Number(pixels);
1930
+ if (intValue.constructor != Number ||
1931
+ intValue < 0 ) {
1932
+ this.mouseSpeed = Selenium.DEFAULT_MOUSE_SPEED;
1933
+ } else {
1934
+ this.mouseSpeed = pixels;
1935
+ }
1936
+ }
1937
+
1938
+ Selenium.prototype.getMouseSpeed = function() {
1939
+ /** Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
1940
+ *
1941
+ * @return number the number of pixels between "mousemove" events during dragAndDrop commands (default=10)
1942
+ */
1943
+ return this.mouseSpeed;
1944
+ }
1945
+
1946
+
1947
+ Selenium.prototype.doDragAndDrop = function(locator, movementsString) {
1948
+ /** Drags an element a certain distance and then drops it
1949
+ * @param locator an element locator
1950
+ * @param movementsString offset in pixels from the current location to which the element should be moved, e.g., "+70,-300"
1951
+ */
1952
+ var element = this.browserbot.findElement(locator);
1953
+ var clientStartXY = getClientXY(element)
1954
+ var clientStartX = clientStartXY[0];
1955
+ var clientStartY = clientStartXY[1];
1956
+
1957
+ var movements = movementsString.split(/,/);
1958
+ var movementX = Number(movements[0]);
1959
+ var movementY = Number(movements[1]);
1960
+
1961
+ var clientFinishX = ((clientStartX + movementX) < 0) ? 0 : (clientStartX + movementX);
1962
+ var clientFinishY = ((clientStartY + movementY) < 0) ? 0 : (clientStartY + movementY);
1963
+
1964
+ var mouseSpeed = this.mouseSpeed;
1965
+ var move = function(current, dest) {
1966
+ if (current == dest) return current;
1967
+ if (Math.abs(current - dest) < mouseSpeed) return dest;
1968
+ return (current < dest) ? current + mouseSpeed : current - mouseSpeed;
1969
+ }
1970
+
1971
+ this.browserbot.triggerMouseEvent(element, 'mousedown', true, clientStartX, clientStartY);
1972
+ this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientStartX, clientStartY);
1973
+ var clientX = clientStartX;
1974
+ var clientY = clientStartY;
1975
+
1976
+ while ((clientX != clientFinishX) || (clientY != clientFinishY)) {
1977
+ clientX = move(clientX, clientFinishX);
1978
+ clientY = move(clientY, clientFinishY);
1979
+ this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientX, clientY);
1980
+ }
1981
+
1982
+ this.browserbot.triggerMouseEvent(element, 'mousemove', true, clientFinishX, clientFinishY);
1983
+ this.browserbot.triggerMouseEvent(element, 'mouseup', true, clientFinishX, clientFinishY);
1984
+ };
1985
+
1986
+ Selenium.prototype.doDragAndDropToObject = function(locatorOfObjectToBeDragged, locatorOfDragDestinationObject) {
1987
+ /** Drags an element and drops it on another element
1988
+ *
1989
+ * @param locatorOfObjectToBeDragged an element to be dragged
1990
+ * @param locatorOfDragDestinationObject an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped
1991
+ */
1992
+ var startX = this.getElementPositionLeft(locatorOfObjectToBeDragged);
1993
+ var startY = this.getElementPositionTop(locatorOfObjectToBeDragged);
1994
+
1995
+ var destinationLeftX = this.getElementPositionLeft(locatorOfDragDestinationObject);
1996
+ var destinationTopY = this.getElementPositionTop(locatorOfDragDestinationObject);
1997
+ var destinationWidth = this.getElementWidth(locatorOfDragDestinationObject);
1998
+ var destinationHeight = this.getElementHeight(locatorOfDragDestinationObject);
1999
+
2000
+ var endX = Math.round(destinationLeftX + (destinationWidth / 2));
2001
+ var endY = Math.round(destinationTopY + (destinationHeight / 2));
2002
+
2003
+ var deltaX = endX - startX;
2004
+ var deltaY = endY - startY;
2005
+
2006
+ var movementsString = "" + deltaX + "," + deltaY;
2007
+
2008
+ this.doDragAndDrop(locatorOfObjectToBeDragged, movementsString);
2009
+ };
2010
+
2011
+ Selenium.prototype.doWindowFocus = function() {
2012
+ /** Gives focus to the currently selected window
2013
+ *
2014
+ */
2015
+ this.browserbot.getCurrentWindow().focus();
2016
+ };
2017
+
2018
+
2019
+ Selenium.prototype.doWindowMaximize = function() {
2020
+ /** Resize currently selected window to take up the entire screen
2021
+ *
2022
+ */
2023
+ var window = this.browserbot.getCurrentWindow();
2024
+ if (window!=null && window.screen) {
2025
+ window.moveTo(0,0);
2026
+ window.resizeTo(screen.availWidth, screen.availHeight);
2027
+ }
2028
+ };
2029
+
2030
+ Selenium.prototype.getAllWindowIds = function() {
2031
+ /** Returns the IDs of all windows that the browser knows about in an array.
2032
+ *
2033
+ * @return string[] Array of identifiers of all windows that the browser knows about.
2034
+ */
2035
+ return this.getAttributeFromAllWindows("id");
2036
+ };
2037
+
2038
+ Selenium.prototype.getAllWindowNames = function() {
2039
+ /** Returns the names of all windows that the browser knows about in an array.
2040
+ *
2041
+ * @return string[] Array of names of all windows that the browser knows about.
2042
+ */
2043
+ return this.getAttributeFromAllWindows("name");
2044
+ };
2045
+
2046
+ Selenium.prototype.getAllWindowTitles = function() {
2047
+ /** Returns the titles of all windows that the browser knows about in an array.
2048
+ *
2049
+ * @return string[] Array of titles of all windows that the browser knows about.
2050
+ */
2051
+ return this.getAttributeFromAllWindows("document.title");
2052
+ };
2053
+
2054
+ Selenium.prototype.getHtmlSource = function() {
2055
+ /** Returns the entire HTML source between the opening and
2056
+ * closing "html" tags.
2057
+ *
2058
+ * @return string the entire HTML source
2059
+ */
2060
+ return this.browserbot.getDocument().getElementsByTagName("html")[0].innerHTML;
2061
+ };
2062
+
2063
+ Selenium.prototype.doSetCursorPosition = function(locator, position) {
2064
+ /**
2065
+ * Moves the text cursor to the specified position in the given input element or textarea.
2066
+ * This method will fail if the specified element isn't an input element or textarea.
2067
+ *
2068
+ * @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
2069
+ * @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.
2070
+ */
2071
+ var element = this.browserbot.findElement(locator);
2072
+ if (element.value == undefined) {
2073
+ Assert.fail("Element " + locator + " is not an input.");
2074
+ }
2075
+ if (position == -1) {
2076
+ position = element.value.length;
2077
+ }
2078
+
2079
+ if( element.setSelectionRange && !browserVersion.isOpera) {
2080
+ element.focus();
2081
+ element.setSelectionRange(/*start*/position,/*end*/position);
2082
+ }
2083
+ else if( element.createTextRange ) {
2084
+ triggerEvent(element, 'focus', false);
2085
+ var range = element.createTextRange();
2086
+ range.collapse(true);
2087
+ range.moveEnd('character',position);
2088
+ range.moveStart('character',position);
2089
+ range.select();
2090
+ }
2091
+ }
2092
+
2093
+ Selenium.prototype.getElementIndex = function(locator) {
2094
+ /**
2095
+ * Get the relative index of an element to its parent (starting from 0). The comment node and empty text node
2096
+ * will be ignored.
2097
+ *
2098
+ * @param locator an <a href="#locators">element locator</a> pointing to an element
2099
+ * @return number of relative index of the element to its parent (starting from 0)
2100
+ */
2101
+ var element = this.browserbot.findElement(locator);
2102
+ var previousSibling;
2103
+ var index = 0;
2104
+ while ((previousSibling = element.previousSibling) != null) {
2105
+ if (!this._isCommentOrEmptyTextNode(previousSibling)) {
2106
+ index++;
2107
+ }
2108
+ element = previousSibling;
2109
+ }
2110
+ return index;
2111
+ }
2112
+
2113
+ Selenium.prototype.isOrdered = function(locator1, locator2) {
2114
+ /**
2115
+ * Check if these two elements have same parent and are ordered siblings in the DOM. Two same elements will
2116
+ * not be considered ordered.
2117
+ *
2118
+ * @param locator1 an <a href="#locators">element locator</a> pointing to the first element
2119
+ * @param locator2 an <a href="#locators">element locator</a> pointing to the second element
2120
+ * @return boolean true if element1 is the previous sibling of element2, false otherwise
2121
+ */
2122
+ var element1 = this.browserbot.findElement(locator1);
2123
+ var element2 = this.browserbot.findElement(locator2);
2124
+ if (element1 === element2) return false;
2125
+
2126
+ var previousSibling;
2127
+ while ((previousSibling = element2.previousSibling) != null) {
2128
+ if (previousSibling === element1) {
2129
+ return true;
2130
+ }
2131
+ element2 = previousSibling;
2132
+ }
2133
+ return false;
2134
+ }
2135
+
2136
+ Selenium.prototype._isCommentOrEmptyTextNode = function(node) {
2137
+ return node.nodeType == 8 || ((node.nodeType == 3) && !(/[^\t\n\r ]/.test(node.data)));
2138
+ }
2139
+
2140
+ Selenium.prototype.getElementPositionLeft = function(locator) {
2141
+ /**
2142
+ * Retrieves the horizontal position of an element
2143
+ *
2144
+ * @param locator an <a href="#locators">element locator</a> pointing to an element OR an element itself
2145
+ * @return number of pixels from the edge of the frame.
2146
+ */
2147
+ var element;
2148
+ if ("string"==typeof locator) {
2149
+ element = this.browserbot.findElement(locator);
2150
+ }
2151
+ else {
2152
+ element = locator;
2153
+ }
2154
+ var x = element.offsetLeft;
2155
+ var elementParent = element.offsetParent;
2156
+
2157
+ while (elementParent != null)
2158
+ {
2159
+ if(document.all)
2160
+ {
2161
+ if( (elementParent.tagName != "TABLE") && (elementParent.tagName != "BODY") )
2162
+ {
2163
+ x += elementParent.clientLeft;
2164
+ }
2165
+ }
2166
+ else // Netscape/DOM
2167
+ {
2168
+ if(elementParent.tagName == "TABLE")
2169
+ {
2170
+ var parentBorder = parseInt(elementParent.border);
2171
+ if(isNaN(parentBorder))
2172
+ {
2173
+ var parentFrame = elementParent.getAttribute('frame');
2174
+ if(parentFrame != null)
2175
+ {
2176
+ x += 1;
2177
+ }
2178
+ }
2179
+ else if(parentBorder > 0)
2180
+ {
2181
+ x += parentBorder;
2182
+ }
2183
+ }
2184
+ }
2185
+ x += elementParent.offsetLeft;
2186
+ elementParent = elementParent.offsetParent;
2187
+ }
2188
+ return x;
2189
+ };
2190
+
2191
+ Selenium.prototype.getElementPositionTop = function(locator) {
2192
+ /**
2193
+ * Retrieves the vertical position of an element
2194
+ *
2195
+ * @param locator an <a href="#locators">element locator</a> pointing to an element OR an element itself
2196
+ * @return number of pixels from the edge of the frame.
2197
+ */
2198
+ var element;
2199
+ if ("string"==typeof locator) {
2200
+ element = this.browserbot.findElement(locator);
2201
+ }
2202
+ else {
2203
+ element = locator;
2204
+ }
2205
+
2206
+ var y = 0;
2207
+
2208
+ while (element != null)
2209
+ {
2210
+ if(document.all)
2211
+ {
2212
+ if( (element.tagName != "TABLE") && (element.tagName != "BODY") )
2213
+ {
2214
+ y += element.clientTop;
2215
+ }
2216
+ }
2217
+ else // Netscape/DOM
2218
+ {
2219
+ if(element.tagName == "TABLE")
2220
+ {
2221
+ var parentBorder = parseInt(element.border);
2222
+ if(isNaN(parentBorder))
2223
+ {
2224
+ var parentFrame = element.getAttribute('frame');
2225
+ if(parentFrame != null)
2226
+ {
2227
+ y += 1;
2228
+ }
2229
+ }
2230
+ else if(parentBorder > 0)
2231
+ {
2232
+ y += parentBorder;
2233
+ }
2234
+ }
2235
+ }
2236
+ y += element.offsetTop;
2237
+
2238
+ // Netscape can get confused in some cases, such that the height of the parent is smaller
2239
+ // than that of the element (which it shouldn't really be). If this is the case, we need to
2240
+ // exclude this element, since it will result in too large a 'top' return value.
2241
+ if (element.offsetParent && element.offsetParent.offsetHeight && element.offsetParent.offsetHeight < element.offsetHeight)
2242
+ {
2243
+ // skip the parent that's too small
2244
+ element = element.offsetParent.offsetParent;
2245
+ }
2246
+ else
2247
+ {
2248
+ // Next up...
2249
+ element = element.offsetParent;
2250
+ }
2251
+ }
2252
+ return y;
2253
+ };
2254
+
2255
+ Selenium.prototype.getElementWidth = function(locator) {
2256
+ /**
2257
+ * Retrieves the width of an element
2258
+ *
2259
+ * @param locator an <a href="#locators">element locator</a> pointing to an element
2260
+ * @return number width of an element in pixels
2261
+ */
2262
+ var element = this.browserbot.findElement(locator);
2263
+ return element.offsetWidth;
2264
+ };
2265
+
2266
+ Selenium.prototype.getElementHeight = function(locator) {
2267
+ /**
2268
+ * Retrieves the height of an element
2269
+ *
2270
+ * @param locator an <a href="#locators">element locator</a> pointing to an element
2271
+ * @return number height of an element in pixels
2272
+ */
2273
+ var element = this.browserbot.findElement(locator);
2274
+ return element.offsetHeight;
2275
+ };
2276
+
2277
+ Selenium.prototype.getCursorPosition = function(locator) {
2278
+ /**
2279
+ * Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers.
2280
+ *
2281
+ * <p>Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to
2282
+ * 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>
2283
+ * This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element.
2284
+ *
2285
+ * @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
2286
+ * @return number the numerical position of the cursor in the field
2287
+ */
2288
+ var element = this.browserbot.findElement(locator);
2289
+ var doc = this.browserbot.getDocument();
2290
+ var win = this.browserbot.getCurrentWindow();
2291
+ if( doc.selection && !browserVersion.isOpera){
2292
+ try {
2293
+ var selectRange = doc.selection.createRange().duplicate();
2294
+ var elementRange = element.createTextRange();
2295
+ selectRange.move("character",0);
2296
+ elementRange.move("character",0);
2297
+ var inRange1 = selectRange.inRange(elementRange);
2298
+ var inRange2 = elementRange.inRange(selectRange);
2299
+ elementRange.setEndPoint("EndToEnd", selectRange);
2300
+ } catch (e) {
2301
+ Assert.fail("There is no cursor on this page!");
2302
+ }
2303
+ var answer = String(elementRange.text).replace(/\r/g,"").length;
2304
+ return answer;
2305
+ } else {
2306
+ if (typeof(element.selectionStart) != "undefined") {
2307
+ if (win.getSelection && typeof(win.getSelection().rangeCount) != undefined && win.getSelection().rangeCount == 0) {
2308
+ Assert.fail("There is no cursor on this page!");
2309
+ }
2310
+ return element.selectionStart;
2311
+ }
2312
+ }
2313
+ throw new Error("Couldn't detect cursor position on this browser!");
2314
+ }
2315
+
2316
+
2317
+ Selenium.prototype.getExpression = function(expression) {
2318
+ /**
2319
+ * Returns the specified expression.
2320
+ *
2321
+ * <p>This is useful because of JavaScript preprocessing.
2322
+ * It is used to generate commands like assertExpression and waitForExpression.</p>
2323
+ *
2324
+ * @param expression the value to return
2325
+ * @return string the value passed in
2326
+ */
2327
+ return expression;
2328
+ }
2329
+
2330
+ Selenium.prototype.getXpathCount = function(xpath) {
2331
+ /**
2332
+ * Returns the number of nodes that match the specified xpath, eg. "//table" would give
2333
+ * the number of tables.
2334
+ *
2335
+ * @param xpath the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.
2336
+ * @return number the number of nodes that match the specified xpath
2337
+ */
2338
+ var result = this.browserbot.evaluateXPathCount(xpath, this.browserbot.getDocument());
2339
+ return result;
2340
+ }
2341
+
2342
+ Selenium.prototype.doAssignId = function(locator, identifier) {
2343
+ /**
2344
+ * Temporarily sets the "id" attribute of the specified element, so you can locate it in the future
2345
+ * using its ID rather than a slow/complicated XPath. This ID will disappear once the page is
2346
+ * reloaded.
2347
+ * @param locator an <a href="#locators">element locator</a> pointing to an element
2348
+ * @param identifier a string to be used as the ID of the specified element
2349
+ */
2350
+ var element = this.browserbot.findElement(locator);
2351
+ element.id = identifier;
2352
+ }
2353
+
2354
+ Selenium.prototype.doAllowNativeXpath = function(allow) {
2355
+ /**
2356
+ * Specifies whether Selenium should use the native in-browser implementation
2357
+ * of XPath (if any native version is available); if you pass "false" to
2358
+ * this function, we will always use our pure-JavaScript xpath library.
2359
+ * Using the pure-JS xpath library can improve the consistency of xpath
2360
+ * element locators between different browser vendors, but the pure-JS
2361
+ * version is much slower than the native implementations.
2362
+ * @param allow boolean, true means we'll prefer to use native XPath; false means we'll only use JS XPath
2363
+ */
2364
+ if ("false" == allow || "0" == allow) { // The strings "false" and "0" are true values in JS
2365
+ allow = false;
2366
+ }
2367
+ this.browserbot.setAllowNativeXPath(allow);
2368
+ }
2369
+
2370
+ Selenium.prototype.doIgnoreAttributesWithoutValue = function(ignore) {
2371
+ /**
2372
+ * Specifies whether Selenium will ignore xpath attributes that have no
2373
+ * value, i.e. are the empty string, when using the non-native xpath
2374
+ * evaluation engine. You'd want to do this for performance reasons in IE.
2375
+ * However, this could break certain xpaths, for example an xpath that looks
2376
+ * for an attribute whose value is NOT the empty string.
2377
+ *
2378
+ * The hope is that such xpaths are relatively rare, but the user should
2379
+ * have the option of using them. Note that this only influences xpath
2380
+ * evaluation when using the ajaxslt engine (i.e. not "javascript-xpath").
2381
+ *
2382
+ * @param ignore boolean, true means we'll ignore attributes without value
2383
+ * at the expense of xpath "correctness"; false means
2384
+ * we'll sacrifice speed for correctness.
2385
+ */
2386
+ if ('false' == ignore || '0' == ignore) {
2387
+ ignore = false;
2388
+ }
2389
+ this.browserbot.setIgnoreAttributesWithoutValue(ignore);
2390
+ }
2391
+
2392
+ Selenium.prototype.doWaitForCondition = function(script, timeout) {
2393
+ /**
2394
+ * Runs the specified JavaScript snippet repeatedly until it evaluates to "true".
2395
+ * The snippet may have multiple lines, but only the result of the last line
2396
+ * will be considered.
2397
+ *
2398
+ * <p>Note that, by default, the snippet will be run in the runner's test window, not in the window
2399
+ * of your application. To get the window of your application, you can use
2400
+ * the JavaScript snippet <code>selenium.browserbot.getCurrentWindow()</code>, and then
2401
+ * run your JavaScript in there</p>
2402
+ * @param script the JavaScript snippet to run
2403
+ * @param timeout a timeout in milliseconds, after which this command will return with an error
2404
+ */
2405
+
2406
+ return Selenium.decorateFunctionWithTimeout(function () {
2407
+ var window = selenium.browserbot.getCurrentWindow();
2408
+ return eval(script);
2409
+ }, timeout);
2410
+ };
2411
+
2412
+ Selenium.prototype.doWaitForCondition.dontCheckAlertsAndConfirms = true;
2413
+
2414
+ Selenium.prototype.doSetTimeout = function(timeout) {
2415
+ /**
2416
+ * Specifies the amount of time that Selenium will wait for actions to complete.
2417
+ *
2418
+ * <p>Actions that require waiting include "open" and the "waitFor*" actions.</p>
2419
+ * The default timeout is 30 seconds.
2420
+ * @param timeout a timeout in milliseconds, after which the action will return with an error
2421
+ */
2422
+ if (!timeout) {
2423
+ timeout = Selenium.DEFAULT_TIMEOUT;
2424
+ }
2425
+ this.defaultTimeout = timeout;
2426
+ }
2427
+
2428
+ Selenium.prototype.doWaitForPageToLoad = function(timeout) {
2429
+ /**
2430
+ * Waits for a new page to load.
2431
+ *
2432
+ * <p>You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc.
2433
+ * (which are only available in the JS API).</p>
2434
+ *
2435
+ * <p>Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded"
2436
+ * flag when it first notices a page load. Running any other Selenium command after
2437
+ * turns the flag to false. Hence, if you want to wait for a page to load, you must
2438
+ * wait immediately after a Selenium command that caused a page-load.</p>
2439
+ * @param timeout a timeout in milliseconds, after which this command will return with an error
2440
+ */
2441
+ // in pi-mode, the test and the harness share the window; thus if we are executing this code, then we have loaded
2442
+ if (window["proxyInjectionMode"] == null || !window["proxyInjectionMode"]) {
2443
+ return this.makePageLoadCondition(timeout);
2444
+ }
2445
+ };
2446
+
2447
+ Selenium.prototype.doWaitForFrameToLoad = function(frameAddress, timeout) {
2448
+ /**
2449
+ * Waits for a new frame to load.
2450
+ *
2451
+ * <p>Selenium constantly keeps track of new pages and frames loading,
2452
+ * and sets a "newPageLoaded" flag when it first notices a page load.</p>
2453
+ *
2454
+ * See waitForPageToLoad for more information.
2455
+ *
2456
+ * @param frameAddress FrameAddress from the server side
2457
+ * @param timeout a timeout in milliseconds, after which this command will return with an error
2458
+ */
2459
+ // in pi-mode, the test and the harness share the window; thus if we are executing this code, then we have loaded
2460
+ if (window["proxyInjectionMode"] == null || !window["proxyInjectionMode"]) {
2461
+ return this.makePageLoadCondition(timeout);
2462
+ }
2463
+ };
2464
+
2465
+ Selenium.prototype._isNewPageLoaded = function() {
2466
+ return this.browserbot.isNewPageLoaded();
2467
+ };
2468
+
2469
+ Selenium.prototype._abortXhrRequest = function() {
2470
+ return this.browserbot.abortXhrRequest();
2471
+ };
2472
+
2473
+ Selenium.prototype.doWaitForPageToLoad.dontCheckAlertsAndConfirms = true;
2474
+
2475
+ /**
2476
+ * Evaluate a parameter, performing JavaScript evaluation and variable substitution.
2477
+ * If the string matches the pattern "javascript{ ... }", evaluate the string between the braces.
2478
+ */
2479
+ Selenium.prototype.preprocessParameter = function(value) {
2480
+ var match = value.match(/^javascript\{((.|\r?\n)+)\}$/);
2481
+ if (match && match[1]) {
2482
+ return eval(match[1]).toString();
2483
+ }
2484
+ return this.replaceVariables(value);
2485
+ };
2486
+
2487
+ /*
2488
+ * Search through str and replace all variable references ${varName} with their
2489
+ * value in storedVars.
2490
+ */
2491
+ Selenium.prototype.replaceVariables = function(str) {
2492
+ var stringResult = str;
2493
+
2494
+ // Find all of the matching variable references
2495
+ var match = stringResult.match(/\$\{\w+\}/g);
2496
+ if (!match) {
2497
+ return stringResult;
2498
+ }
2499
+
2500
+ // For each match, lookup the variable value, and replace if found
2501
+ for (var i = 0; match && i < match.length; i++) {
2502
+ var variable = match[i]; // The replacement variable, with ${}
2503
+ var name = variable.substring(2, variable.length - 1); // The replacement variable without ${}
2504
+ var replacement = storedVars[name];
2505
+ if (replacement != undefined) {
2506
+ stringResult = stringResult.replace(variable, replacement);
2507
+ }
2508
+ }
2509
+ return stringResult;
2510
+ };
2511
+
2512
+ Selenium.prototype.getCookie = function() {
2513
+ /**
2514
+ * Return all cookies of the current page under test.
2515
+ *
2516
+ * @return string all cookies of the current page under test
2517
+ */
2518
+ var doc = this.browserbot.getDocument();
2519
+ return doc.cookie;
2520
+ };
2521
+
2522
+ Selenium.prototype.getCookieByName = function(name) {
2523
+ /**
2524
+ * Returns the value of the cookie with the specified name, or throws an error if the cookie is not present.
2525
+ * @param name the name of the cookie
2526
+ * @return string the value of the cookie
2527
+ */
2528
+ var v = this.browserbot.getCookieByName(name);
2529
+ if (v === null) {
2530
+ throw new SeleniumError("Cookie '"+name+"' was not found");
2531
+ }
2532
+ return v;
2533
+ };
2534
+
2535
+ Selenium.prototype.isCookiePresent = function(name) {
2536
+ /**
2537
+ * Returns true if a cookie with the specified name is present, or false otherwise.
2538
+ * @param name the name of the cookie
2539
+ * @return boolean true if a cookie with the specified name is present, or false otherwise.
2540
+ */
2541
+ var v = this.browserbot.getCookieByName(name);
2542
+ var absent = (v === null);
2543
+ return !absent;
2544
+ }
2545
+
2546
+ Selenium.prototype.doCreateCookie = function(nameValuePair, optionsString) {
2547
+ /**
2548
+ * Create a new cookie whose path and domain are same with those of current page
2549
+ * under test, unless you specified a path for this cookie explicitly.
2550
+ *
2551
+ * @param nameValuePair name and value of the cookie in a format "name=value"
2552
+ * @param optionsString options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'.
2553
+ * the optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are irrelevant, the unit
2554
+ * of the value of 'max_age' is second. Note that specifying a domain that isn't a subset of the current domain will
2555
+ * usually fail.
2556
+ */
2557
+ var results = /[^\s=\[\]\(\),"\/\?@:;]+=[^\s=\[\]\(\),"\/\?@:;]*/.test(nameValuePair);
2558
+ if (!results) {
2559
+ throw new SeleniumError("Invalid parameter.");
2560
+ }
2561
+ var cookie = nameValuePair.trim();
2562
+ results = /max_age=(\d+)/.exec(optionsString);
2563
+ if (results) {
2564
+ var expireDateInMilliseconds = (new Date()).getTime() + results[1] * 1000;
2565
+ cookie += "; expires=" + new Date(expireDateInMilliseconds).toGMTString();
2566
+ }
2567
+ results = /path=([^\s,]+)[,]?/.exec(optionsString);
2568
+ if (results) {
2569
+ var path = results[1];
2570
+ if (browserVersion.khtml) {
2571
+ // Safari and conquerer don't like paths with / at the end
2572
+ if ("/" != path) {
2573
+ path = path.replace(/\/$/, "");
2574
+ }
2575
+ }
2576
+ cookie += "; path=" + path;
2577
+ }
2578
+ results = /domain=([^\s,]+)[,]?/.exec(optionsString);
2579
+ if (results) {
2580
+ var domain = results[1];
2581
+ cookie += "; domain=" + domain;
2582
+ }
2583
+ LOG.debug("Setting cookie to: " + cookie);
2584
+ this.browserbot.getDocument().cookie = cookie;
2585
+ }
2586
+
2587
+ Selenium.prototype.doDeleteCookie = function(name,optionsString) {
2588
+ /**
2589
+ * Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you
2590
+ * need to delete it using the exact same path and domain that were used to create the cookie.
2591
+ * If the path is wrong, or the domain is wrong, the cookie simply won't be deleted. Also
2592
+ * note that specifying a domain that isn't a subset of the current domain will usually fail.
2593
+ *
2594
+ * Since there's no way to discover at runtime the original path and domain of a given cookie,
2595
+ * we've added an option called 'recurse' to try all sub-domains of the current domain with
2596
+ * all paths that are a subset of the current path. Beware; this option can be slow. In
2597
+ * big-O notation, it operates in O(n*m) time, where n is the number of dots in the domain
2598
+ * name and m is the number of slashes in the path.
2599
+ *
2600
+ * @param name the name of the cookie to be deleted
2601
+ * @param optionsString options for the cookie. Currently supported options include 'path', 'domain'
2602
+ * and 'recurse.' The optionsString's format is "path=/path/, domain=.foo.com, recurse=true".
2603
+ * The order of options are irrelevant. Note that specifying a domain that isn't a subset of
2604
+ * the current domain will usually fail.
2605
+ */
2606
+ // set the expire time of the cookie to be deleted to one minute before now.
2607
+ var path = "";
2608
+ var domain = "";
2609
+ var recurse = false;
2610
+ var matched = false;
2611
+ results = /path=([^\s,]+)[,]?/.exec(optionsString);
2612
+ if (results) {
2613
+ matched = true;
2614
+ path = results[1];
2615
+ }
2616
+ results = /domain=([^\s,]+)[,]?/.exec(optionsString);
2617
+ if (results) {
2618
+ matched = true;
2619
+ domain = results[1];
2620
+ }
2621
+ results = /recurse=([^\s,]+)[,]?/.exec(optionsString);
2622
+ if (results) {
2623
+ matched = true;
2624
+ recurse = results[1];
2625
+ if ("false" == recurse) {
2626
+ recurse = false;
2627
+ }
2628
+ }
2629
+ // Treat the entire optionsString as a path (for backwards compatibility)
2630
+ if (optionsString && !matched) {
2631
+ LOG.warn("Using entire optionsString as a path; please change the argument to deleteCookie to use path="+optionsString);
2632
+ path = optionsString;
2633
+ }
2634
+ if (browserVersion.khtml) {
2635
+ // Safari and conquerer don't like paths with / at the end
2636
+ if ("/" != path) {
2637
+ path = path.replace(/\/$/, "");
2638
+ }
2639
+ }
2640
+ path = path.trim();
2641
+ domain = domain.trim();
2642
+ var cookieName = name.trim();
2643
+ if (recurse) {
2644
+ this.browserbot.recursivelyDeleteCookie(cookieName, domain, path);
2645
+ } else {
2646
+ this.browserbot.deleteCookie(cookieName, domain, path);
2647
+ }
2648
+ }
2649
+
2650
+ Selenium.prototype.doDeleteAllVisibleCookies = function() {
2651
+ /** Calls deleteCookie with recurse=true on all cookies visible to the current page.
2652
+ * As noted on the documentation for deleteCookie, recurse=true can be much slower
2653
+ * than simply deleting the cookies using a known domain/path.
2654
+ */
2655
+ var win = this.browserbot.getCurrentWindow();
2656
+ var doc = win.document;
2657
+ var cookieNames = this.browserbot.getAllCookieNames(doc);
2658
+ var domain = doc.domain;
2659
+ var path = win.location.pathname;
2660
+ for (var i = 0; i < cookieNames.length; i++) {
2661
+ this.browserbot.recursivelyDeleteCookie(cookieNames[i], domain, path, win);
2662
+ }
2663
+ }
2664
+
2665
+ Selenium.prototype.doSetBrowserLogLevel = function(logLevel) {
2666
+ /**
2667
+ * Sets the threshold for browser-side logging messages; log messages beneath this threshold will be discarded.
2668
+ * Valid logLevel strings are: "debug", "info", "warn", "error" or "off".
2669
+ * To see the browser logs, you need to
2670
+ * either show the log window in GUI mode, or enable browser-side logging in Selenium RC.
2671
+ *
2672
+ * @param logLevel one of the following: "debug", "info", "warn", "error" or "off"
2673
+ */
2674
+ if (logLevel == null || logLevel == "") {
2675
+ throw new SeleniumError("You must specify a log level");
2676
+ }
2677
+ logLevel = logLevel.toLowerCase();
2678
+ if (LOG.logLevels[logLevel] == null) {
2679
+ throw new SeleniumError("Invalid log level: " + logLevel);
2680
+ }
2681
+ LOG.setLogLevelThreshold(logLevel);
2682
+ }
2683
+
2684
+ Selenium.prototype.doRunScript = function(script) {
2685
+ /**
2686
+ * Creates a new "script" tag in the body of the current test window, and
2687
+ * adds the specified text into the body of the command. Scripts run in
2688
+ * this way can often be debugged more easily than scripts executed using
2689
+ * Selenium's "getEval" command. Beware that JS exceptions thrown in these script
2690
+ * tags aren't managed by Selenium, so you should probably wrap your script
2691
+ * in try/catch blocks if there is any chance that the script will throw
2692
+ * an exception.
2693
+ * @param script the JavaScript snippet to run
2694
+ */
2695
+ var win = this.browserbot.getCurrentWindow();
2696
+ var doc = win.document;
2697
+ var scriptTag = doc.createElement("script");
2698
+ scriptTag.type = "text/javascript"
2699
+ scriptTag.text = script;
2700
+ doc.body.appendChild(scriptTag);
2701
+ }
2702
+
2703
+ Selenium.prototype.doAddLocationStrategy = function(strategyName, functionDefinition) {
2704
+ /**
2705
+ * Defines a new function for Selenium to locate elements on the page.
2706
+ * For example,
2707
+ * if you define the strategy "foo", and someone runs click("foo=blah"), we'll
2708
+ * run your function, passing you the string "blah", and click on the element
2709
+ * that your function
2710
+ * returns, or throw an "Element not found" error if your function returns null.
2711
+ *
2712
+ * We'll pass three arguments to your function:
2713
+ * <ul>
2714
+ * <li>locator: the string the user passed in</li>
2715
+ * <li>inWindow: the currently selected window</li>
2716
+ * <li>inDocument: the currently selected document</li>
2717
+ * </ul>
2718
+ * The function must return null if the element can't be found.
2719
+ *
2720
+ * @param strategyName the name of the strategy to define; this should use only
2721
+ * letters [a-zA-Z] with no spaces or other punctuation.
2722
+ * @param functionDefinition a string defining the body of a function in JavaScript.
2723
+ * For example: <code>return inDocument.getElementById(locator);</code>
2724
+ */
2725
+ if (!/^[a-zA-Z]+$/.test(strategyName)) {
2726
+ throw new SeleniumError("Invalid strategy name: " + strategyName);
2727
+ }
2728
+ var strategyFunction;
2729
+ try {
2730
+ strategyFunction = new Function("locator", "inDocument", "inWindow", functionDefinition);
2731
+ } catch (ex) {
2732
+ throw new SeleniumError("Error evaluating function definition: " + extractExceptionMessage(ex));
2733
+ }
2734
+ var safeStrategyFunction = function() {
2735
+ try {
2736
+ return strategyFunction.apply(this, arguments);
2737
+ } catch (ex) {
2738
+ throw new SeleniumError("Error executing strategy function " + strategyName + ": " + extractExceptionMessage(ex));
2739
+ }
2740
+ }
2741
+ this.browserbot.locationStrategies[strategyName] = safeStrategyFunction;
2742
+ }
2743
+
2744
+ Selenium.prototype.doCaptureEntirePageScreenshot = function(filename, kwargs) {
2745
+ /**
2746
+ * Saves the entire contents of the current window canvas to a PNG file.
2747
+ * Contrast this with the captureScreenshot command, which captures the
2748
+ * contents of the OS viewport (i.e. whatever is currently being displayed
2749
+ * on the monitor), and is implemented in the RC only. Currently this only
2750
+ * works in Firefox when running in chrome mode, and in IE non-HTA using
2751
+ * the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly
2752
+ * borrowed from the Screengrab! Firefox extension. Please see
2753
+ * http://www.screengrab.org and http://snapsie.sourceforge.net/ for
2754
+ * details.
2755
+ *
2756
+ * @param filename the path to the file to persist the screenshot as. No
2757
+ * filename extension will be appended by default.
2758
+ * Directories will not be created if they do not exist,
2759
+ * and an exception will be thrown, possibly by native
2760
+ * code.
2761
+ * @param kwargs a kwargs string that modifies the way the screenshot
2762
+ * is captured. Example: "background=#CCFFDD" .
2763
+ * Currently valid options:
2764
+ * <dl>
2765
+ * <dt>background</dt>
2766
+ * <dd>the background CSS for the HTML document. This
2767
+ * may be useful to set for capturing screenshots of
2768
+ * less-than-ideal layouts, for example where absolute
2769
+ * positioning causes the calculation of the canvas
2770
+ * dimension to fail and a black background is exposed
2771
+ * (possibly obscuring black text).</dd>
2772
+ * </dl>
2773
+ */
2774
+ if (! browserVersion.isChrome &&
2775
+ ! (browserVersion.isIE && ! browserVersion.isHTA)) {
2776
+ throw new SeleniumError('captureEntirePageScreenshot is only '
2777
+ + 'implemented for Firefox ("firefox" or "chrome", NOT '
2778
+ + '"firefoxproxy") and IE non-HTA ("iexploreproxy", NOT "iexplore" '
2779
+ + 'or "iehta"). The current browser isn\'t one of them!');
2780
+ }
2781
+
2782
+ // do or do not ... there is no try
2783
+
2784
+ if (browserVersion.isIE) {
2785
+ // targeting snapsIE >= 0.2
2786
+ function getFailureMessage(exceptionMessage) {
2787
+ var msg = 'Snapsie failed: ';
2788
+ if (exceptionMessage) {
2789
+ if (exceptionMessage ==
2790
+ "Automation server can't create object") {
2791
+ msg += 'Is it installed? Does it have permission to run '
2792
+ + 'as an add-on? See http://snapsie.sourceforge.net/';
2793
+ }
2794
+ else {
2795
+ msg += exceptionMessage;
2796
+ }
2797
+ }
2798
+ else {
2799
+ msg += 'Undocumented error';
2800
+ }
2801
+ return msg;
2802
+ }
2803
+
2804
+ if (typeof(runOptions) != 'undefined' &&
2805
+ runOptions.isMultiWindowMode() == false) {
2806
+ // framed mode
2807
+ try {
2808
+ new Snapsie().saveSnapshot(filename, 'selenium_myiframe');
2809
+ }
2810
+ catch (e) {
2811
+ throw new SeleniumError(getFailureMessage(e.message));
2812
+ }
2813
+ }
2814
+ else {
2815
+ // multi-window mode
2816
+ if (!this.snapsieSrc) {
2817
+ // XXX - cache snapsie, and capture the screenshot as a
2818
+ // callback. Definitely a hack, because we may be late taking
2819
+ // the first screenshot, but saves us from polluting other code
2820
+ // for now. I wish there were an easier way to get at the
2821
+ // contents of a referenced script!
2822
+ var snapsieUrl = (this.browserbot.buttonWindow.location.href)
2823
+ .replace(/(Test|Remote)Runner\.html/, 'lib/snapsie.js');
2824
+ var self = this;
2825
+ new Ajax.Request(snapsieUrl, {
2826
+ method: 'get'
2827
+ , onSuccess: function(transport) {
2828
+ self.snapsieSrc = transport.responseText;
2829
+ self.doCaptureEntirePageScreenshot(filename, kwargs);
2830
+ }
2831
+ });
2832
+ return;
2833
+ }
2834
+
2835
+ // it's going into a string, so escape the backslashes
2836
+ filename = filename.replace(/\\/g, '\\\\');
2837
+
2838
+ // this is sort of hackish. We insert a script into the document,
2839
+ // and remove it before anyone notices.
2840
+ var doc = selenium.browserbot.getDocument();
2841
+ var script = doc.createElement('script');
2842
+ var scriptContent = this.snapsieSrc
2843
+ + 'try {'
2844
+ + ' new Snapsie().saveSnapshot("' + filename + '");'
2845
+ + '}'
2846
+ + 'catch (e) {'
2847
+ + ' document.getElementById("takeScreenshot").failure ='
2848
+ + ' e.message;'
2849
+ + '}';
2850
+ script.id = 'takeScreenshot';
2851
+ script.language = 'javascript';
2852
+ script.text = scriptContent;
2853
+ doc.body.appendChild(script);
2854
+ script.parentNode.removeChild(script);
2855
+ if (script.failure) {
2856
+ throw new SeleniumError(getFailureMessage(script.failure));
2857
+ }
2858
+ }
2859
+ return;
2860
+ }
2861
+
2862
+ var grabber = {
2863
+ prepareCanvas: function(width, height) {
2864
+ var styleWidth = width + 'px';
2865
+ var styleHeight = height + 'px';
2866
+
2867
+ var grabCanvas = document.getElementById('screenshot_canvas');
2868
+ if (!grabCanvas) {
2869
+ // create the canvas
2870
+ var ns = 'http://www.w3.org/1999/xhtml';
2871
+ grabCanvas = document.createElementNS(ns, 'html:canvas');
2872
+ grabCanvas.id = 'screenshot_canvas';
2873
+ grabCanvas.style.display = 'none';
2874
+ document.documentElement.appendChild(grabCanvas);
2875
+ }
2876
+
2877
+ grabCanvas.width = width;
2878
+ grabCanvas.style.width = styleWidth;
2879
+ grabCanvas.style.maxWidth = styleWidth;
2880
+ grabCanvas.height = height;
2881
+ grabCanvas.style.height = styleHeight;
2882
+ grabCanvas.style.maxHeight = styleHeight;
2883
+
2884
+ return grabCanvas;
2885
+ },
2886
+
2887
+ prepareContext: function(canvas, box) {
2888
+ var context = canvas.getContext('2d');
2889
+ context.clearRect(box.x, box.y, box.width, box.height);
2890
+ context.save();
2891
+ return context;
2892
+ }
2893
+ };
2894
+
2895
+ var SGNsUtils = {
2896
+ dataUrlToBinaryInputStream: function(dataUrl) {
2897
+ var nsIoService = Components.classes["@mozilla.org/network/io-service;1"]
2898
+ .getService(Components.interfaces.nsIIOService);
2899
+ var channel = nsIoService
2900
+ .newChannelFromURI(nsIoService.newURI(dataUrl, null, null));
2901
+ var binaryInputStream = Components.classes["@mozilla.org/binaryinputstream;1"]
2902
+ .createInstance(Components.interfaces.nsIBinaryInputStream);
2903
+
2904
+ binaryInputStream.setInputStream(channel.open());
2905
+ return binaryInputStream;
2906
+ },
2907
+
2908
+ newFileOutputStream: function(nsFile) {
2909
+ var writeFlag = 0x02; // write only
2910
+ var createFlag = 0x08; // create
2911
+ var truncateFlag = 0x20; // truncate
2912
+ var fileOutputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
2913
+ .createInstance(Components.interfaces.nsIFileOutputStream);
2914
+
2915
+ fileOutputStream.init(nsFile,
2916
+ writeFlag | createFlag | truncateFlag, 0664, null);
2917
+ return fileOutputStream;
2918
+ },
2919
+
2920
+ writeBinaryInputStreamToFileOutputStream:
2921
+ function(binaryInputStream, fileOutputStream) {
2922
+ var numBytes = binaryInputStream.available();
2923
+ var bytes = binaryInputStream.readBytes(numBytes);
2924
+ fileOutputStream.write(bytes, numBytes);
2925
+ }
2926
+ };
2927
+
2928
+ // compute dimensions
2929
+ var window = this.browserbot.getCurrentWindow();
2930
+ var doc = window.document.documentElement;
2931
+ var box = {
2932
+ x: 0,
2933
+ y: 0,
2934
+ width: doc.scrollWidth,
2935
+ height: doc.scrollHeight
2936
+ };
2937
+ LOG.debug('computed dimensions');
2938
+
2939
+ var originalBackground = doc.style.background;
2940
+
2941
+ if (kwargs) {
2942
+ var args = parse_kwargs(kwargs);
2943
+ if (args.background) {
2944
+ doc.style.background = args.background;
2945
+ }
2946
+ }
2947
+
2948
+ // grab
2949
+ var format = 'png';
2950
+ var canvas = grabber.prepareCanvas(box.width, box.height);
2951
+ var context = grabber.prepareContext(canvas, box);
2952
+ context.drawWindow(window, box.x, box.y, box.width, box.height,
2953
+ 'rgb(0, 0, 0)');
2954
+ context.restore();
2955
+ var dataUrl = canvas.toDataURL("image/" + format);
2956
+ LOG.debug('grabbed to canvas');
2957
+
2958
+ doc.style.background = originalBackground;
2959
+
2960
+ // save to file
2961
+ var nsFile = Components.classes["@mozilla.org/file/local;1"]
2962
+ .createInstance(Components.interfaces.nsILocalFile);
2963
+ try {
2964
+ nsFile.initWithPath(filename);
2965
+ }
2966
+ catch (e) {
2967
+ if (/NS_ERROR_FILE_UNRECOGNIZED_PATH/.test(e.message)) {
2968
+ // try using the opposite file separator
2969
+ if (filename.indexOf('/') != -1) {
2970
+ filename = filename.replace(/\//g, '\\');
2971
+ }
2972
+ else {
2973
+ filename = filename.replace(/\\/g, '/');
2974
+ }
2975
+ nsFile.initWithPath(filename);
2976
+ }
2977
+ else {
2978
+ throw e;
2979
+ }
2980
+ }
2981
+ var binaryInputStream = SGNsUtils.dataUrlToBinaryInputStream(dataUrl);
2982
+ var fileOutputStream = SGNsUtils.newFileOutputStream(nsFile);
2983
+ SGNsUtils.writeBinaryInputStreamToFileOutputStream(binaryInputStream,
2984
+ fileOutputStream);
2985
+ fileOutputStream.close();
2986
+ LOG.debug('saved to file');
2987
+ };
2988
+
2989
+ Selenium.prototype.doRollup = function(rollupName, kwargs) {
2990
+ /**
2991
+ * Executes a command rollup, which is a series of commands with a unique
2992
+ * name, and optionally arguments that control the generation of the set of
2993
+ * commands. If any one of the rolled-up commands fails, the rollup is
2994
+ * considered to have failed. Rollups may also contain nested rollups.
2995
+ *
2996
+ * @param rollupName the name of the rollup command
2997
+ * @param kwargs keyword arguments string that influences how the
2998
+ * rollup expands into commands
2999
+ */
3000
+ // we have to temporarily hijack the commandStarted, nextCommand(),
3001
+ // commandComplete(), and commandError() methods of the TestLoop object.
3002
+ // When the expanded rollup commands are done executing (or an error has
3003
+ // occurred), we'll restore them to their original values.
3004
+ var loop = currentTest || htmlTestRunner.currentTest;
3005
+ var backupManager = {
3006
+ backup: function() {
3007
+ for (var item in this.data) {
3008
+ this.data[item] = loop[item];
3009
+ }
3010
+ }
3011
+ , restore: function() {
3012
+ for (var item in this.data) {
3013
+ loop[item] = this.data[item];
3014
+ }
3015
+ }
3016
+ , data: {
3017
+ requiresCallBack: null
3018
+ , commandStarted: null
3019
+ , nextCommand: null
3020
+ , commandComplete: null
3021
+ , commandError: null
3022
+ , pendingRollupCommands: null
3023
+ , rollupFailed: null
3024
+ , rollupFailedMessage: null
3025
+ }
3026
+ };
3027
+
3028
+ var rule = RollupManager.getInstance().getRollupRule(rollupName);
3029
+ var expandedCommands = rule.getExpandedCommands(kwargs);
3030
+
3031
+ // hold your breath ...
3032
+ try {
3033
+ backupManager.backup();
3034
+ loop.requiresCallBack = false;
3035
+ loop.commandStarted = function() {};
3036
+ loop.nextCommand = function() {
3037
+ if (this.pendingRollupCommands.length == 0) {
3038
+ return null;
3039
+ }
3040
+ var command = this.pendingRollupCommands.shift();
3041
+ return command;
3042
+ };
3043
+ loop.commandComplete = function(result) {
3044
+ if (result.failed) {
3045
+ this.rollupFailed = true;
3046
+ this.rollupFailureMessages.push(result.failureMessage);
3047
+ }
3048
+
3049
+ if (this.pendingRollupCommands.length == 0) {
3050
+ result = {
3051
+ failed: this.rollupFailed
3052
+ , failureMessage: this.rollupFailureMessages.join('; ')
3053
+ };
3054
+ LOG.info('Rollup execution complete: ' + (result.failed
3055
+ ? 'failed! (see error messages below)' : 'ok'));
3056
+ backupManager.restore();
3057
+ this.commandComplete(result);
3058
+ }
3059
+ };
3060
+ loop.commandError = function(errorMessage) {
3061
+ LOG.info('Rollup execution complete: bombed!');
3062
+ backupManager.restore();
3063
+ this.commandError(errorMessage);
3064
+ };
3065
+
3066
+ loop.pendingRollupCommands = expandedCommands;
3067
+ loop.rollupFailed = false;
3068
+ loop.rollupFailureMessages = [];
3069
+ }
3070
+ catch (e) {
3071
+ LOG.error('Rollup error: ' + e);
3072
+ backupManager.restore();
3073
+ }
3074
+ };
3075
+
3076
+ Selenium.prototype.doAddScript = function(scriptContent, scriptTagId) {
3077
+ /**
3078
+ * Loads script content into a new script tag in the Selenium document. This
3079
+ * differs from the runScript command in that runScript adds the script tag
3080
+ * to the document of the AUT, not the Selenium document. The following
3081
+ * entities in the script content are replaced by the characters they
3082
+ * represent:
3083
+ *
3084
+ * &lt;
3085
+ * &gt;
3086
+ * &amp;
3087
+ *
3088
+ * The corresponding remove command is removeScript.
3089
+ *
3090
+ * @param scriptContent the Javascript content of the script to add
3091
+ * @param scriptTagId (optional) the id of the new script tag. If
3092
+ * specified, and an element with this id already
3093
+ * exists, this operation will fail.
3094
+ */
3095
+ if (scriptTagId && document.getElementById(scriptTagId)) {
3096
+ var msg = "Element with id '" + scriptTagId + "' already exists!";
3097
+ throw new SeleniumError(msg);
3098
+ }
3099
+
3100
+ var head = document.getElementsByTagName('head')[0];
3101
+ var script = document.createElement('script');
3102
+
3103
+ script.type = 'text/javascript';
3104
+
3105
+ if (scriptTagId) {
3106
+ script.id = scriptTagId;
3107
+ }
3108
+
3109
+ // replace some entities
3110
+ scriptContent = scriptContent
3111
+ .replace(/&lt;/g, '<')
3112
+ .replace(/&gt;/g, '>')
3113
+ .replace(/&amp;/g, '&');
3114
+
3115
+ script.text = scriptContent;
3116
+ head.appendChild(script);
3117
+ };
3118
+
3119
+ Selenium.prototype.doRemoveScript = function(scriptTagId) {
3120
+ /**
3121
+ * Removes a script tag from the Selenium document identified by the given
3122
+ * id. Does nothing if the referenced tag doesn't exist.
3123
+ *
3124
+ * @param scriptTagId the id of the script element to remove.
3125
+ */
3126
+ var script = document.getElementById(scriptTagId);
3127
+
3128
+ if (script && getTagName(script) == 'script') {
3129
+ script.parentNode.removeChild(script);
3130
+ }
3131
+ };
3132
+
3133
+ Selenium.prototype.doUseXpathLibrary = function(libraryName) {
3134
+ /**
3135
+ * Allows choice of one of the available libraries.
3136
+ * @param libraryName name of the desired library
3137
+ * Only the following can be chosen:
3138
+ * <ul>
3139
+ * <li>"ajaxslt" - Google's library</li>
3140
+ * <li>"javascript-xpath" - Cybozu Labs' faster library</li>
3141
+ * <li>"rpc-optimizing-ajaxslt" - the RPC optimizing strategy, delegating to ajaxslt</li>
3142
+ * <li>"rpc-optimizing-jsxpath" - the RPC optimizing strategy, delegating to javascript-xpath</li>
3143
+ * <li>"default" - The default library. Currently the default library is "ajaxslt" .</li>
3144
+ * </ul>
3145
+ * If libraryName isn't one of these, it may be the name of another engine
3146
+ * registered to the browserbot's XPathEvaluator, for example by overriding
3147
+ * XPathEvaluator.prototype.init() . If it is not a registered engine
3148
+ * either, then no change will be made.
3149
+ */
3150
+
3151
+ if (! this.browserbot.getXPathEngine(libraryName)) {
3152
+ return;
3153
+ }
3154
+
3155
+ this.browserbot.setXPathEngine(libraryName);
3156
+ };
3157
+
3158
+ /**
3159
+ * Factory for creating "Option Locators".
3160
+ * An OptionLocator is an object for dealing with Select options (e.g. for
3161
+ * finding a specified option, or asserting that the selected option of
3162
+ * Select element matches some condition.
3163
+ * The type of locator returned by the factory depends on the locator string:
3164
+ * label=<exp> (OptionLocatorByLabel)
3165
+ * value=<exp> (OptionLocatorByValue)
3166
+ * index=<exp> (OptionLocatorByIndex)
3167
+ * id=<exp> (OptionLocatorById)
3168
+ * <exp> (default is OptionLocatorByLabel).
3169
+ */
3170
+ function OptionLocatorFactory() {
3171
+ }
3172
+
3173
+ OptionLocatorFactory.prototype.fromLocatorString = function(locatorString) {
3174
+ var locatorType = 'label';
3175
+ var locatorValue = locatorString;
3176
+ // If there is a locator prefix, use the specified strategy
3177
+ var result = locatorString.match(/^([a-zA-Z]+)=(.*)/);
3178
+ if (result) {
3179
+ locatorType = result[1];
3180
+ locatorValue = result[2];
3181
+ }
3182
+ if (this.optionLocators == undefined) {
3183
+ this.registerOptionLocators();
3184
+ }
3185
+ if (this.optionLocators[locatorType]) {
3186
+ return new this.optionLocators[locatorType](locatorValue);
3187
+ }
3188
+ throw new SeleniumError("Unknown option locator type: " + locatorType);
3189
+ };
3190
+
3191
+ /**
3192
+ * To allow for easy extension, all of the option locators are found by
3193
+ * searching for all methods of OptionLocatorFactory.prototype that start
3194
+ * with "OptionLocatorBy".
3195
+ * TODO: Consider using the term "Option Specifier" instead of "Option Locator".
3196
+ */
3197
+ OptionLocatorFactory.prototype.registerOptionLocators = function() {
3198
+ this.optionLocators={};
3199
+ for (var functionName in this) {
3200
+ var result = /OptionLocatorBy([A-Z].+)$/.exec(functionName);
3201
+ if (result != null) {
3202
+ var locatorName = result[1].lcfirst();
3203
+ this.optionLocators[locatorName] = this[functionName];
3204
+ }
3205
+ }
3206
+ };
3207
+
3208
+ /**
3209
+ * OptionLocator for options identified by their labels.
3210
+ */
3211
+ OptionLocatorFactory.prototype.OptionLocatorByLabel = function(label) {
3212
+ this.label = label;
3213
+ this.labelMatcher = new PatternMatcher(this.label);
3214
+ this.findOption = function(element) {
3215
+ for (var i = 0; i < element.options.length; i++) {
3216
+ if (this.labelMatcher.matches(element.options[i].text)) {
3217
+ return element.options[i];
3218
+ }
3219
+ }
3220
+ throw new SeleniumError("Option with label '" + this.label + "' not found");
3221
+ };
3222
+
3223
+ this.assertSelected = function(element) {
3224
+ var selectedLabel = element.options[element.selectedIndex].text;
3225
+ Assert.matches(this.label, selectedLabel)
3226
+ };
3227
+ };
3228
+
3229
+ /**
3230
+ * OptionLocator for options identified by their values.
3231
+ */
3232
+ OptionLocatorFactory.prototype.OptionLocatorByValue = function(value) {
3233
+ this.value = value;
3234
+ this.valueMatcher = new PatternMatcher(this.value);
3235
+ this.findOption = function(element) {
3236
+ for (var i = 0; i < element.options.length; i++) {
3237
+ if (this.valueMatcher.matches(element.options[i].value)) {
3238
+ return element.options[i];
3239
+ }
3240
+ }
3241
+ throw new SeleniumError("Option with value '" + this.value + "' not found");
3242
+ };
3243
+
3244
+ this.assertSelected = function(element) {
3245
+ var selectedValue = element.options[element.selectedIndex].value;
3246
+ Assert.matches(this.value, selectedValue)
3247
+ };
3248
+ };
3249
+
3250
+ /**
3251
+ * OptionLocator for options identified by their index.
3252
+ */
3253
+ OptionLocatorFactory.prototype.OptionLocatorByIndex = function(index) {
3254
+ this.index = Number(index);
3255
+ if (isNaN(this.index) || this.index < 0) {
3256
+ throw new SeleniumError("Illegal Index: " + index);
3257
+ }
3258
+
3259
+ this.findOption = function(element) {
3260
+ if (element.options.length <= this.index) {
3261
+ throw new SeleniumError("Index out of range. Only " + element.options.length + " options available");
3262
+ }
3263
+ return element.options[this.index];
3264
+ };
3265
+
3266
+ this.assertSelected = function(element) {
3267
+ Assert.equals(this.index, element.selectedIndex);
3268
+ };
3269
+ };
3270
+
3271
+ /**
3272
+ * OptionLocator for options identified by their id.
3273
+ */
3274
+ OptionLocatorFactory.prototype.OptionLocatorById = function(id) {
3275
+ this.id = id;
3276
+ this.idMatcher = new PatternMatcher(this.id);
3277
+ this.findOption = function(element) {
3278
+ for (var i = 0; i < element.options.length; i++) {
3279
+ if (this.idMatcher.matches(element.options[i].id)) {
3280
+ return element.options[i];
3281
+ }
3282
+ }
3283
+ throw new SeleniumError("Option with id '" + this.id + "' not found");
3284
+ };
3285
+
3286
+ this.assertSelected = function(element) {
3287
+ var selectedId = element.options[element.selectedIndex].id;
3288
+ Assert.matches(this.id, selectedId)
3289
+ };
3290
+ };
3291
+