/testing/selenium-core/scripts/selenium-browserbot.js

http://datanucleus-appengine.googlecode.com/ · JavaScript · 2285 lines · 1743 code · 263 blank · 279 comment · 485 complexity · 37b7d76fc9be9ccd2d0513be52305ee1 MD5 · raw file

Large files are truncated click here to view the full file

  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. * This script provides the Javascript API to drive the test application contained within
  19. * a Browser Window.
  20. * TODO:
  21. * Add support for more events (keyboard and mouse)
  22. * Allow to switch "user-entry" mode from mouse-based to keyboard-based, firing different
  23. * events in different modes.
  24. */
  25. // The window to which the commands will be sent. For example, to click on a
  26. // popup window, first select that window, and then do a normal click command.
  27. var BrowserBot = function(topLevelApplicationWindow) {
  28. this.topWindow = topLevelApplicationWindow;
  29. this.topFrame = this.topWindow;
  30. this.baseUrl=window.location.href;
  31. // the buttonWindow is the Selenium window
  32. // it contains the Run/Pause buttons... this should *not* be the AUT window
  33. this.buttonWindow = window;
  34. this.currentWindow = this.topWindow;
  35. this.currentWindowName = null;
  36. this.allowNativeXpath = true;
  37. this.xpathLibrary = 'ajaxslt' // change to "javascript-xpath" for the newer, faster engine
  38. // We need to know this in advance, in case the frame closes unexpectedly
  39. this.isSubFrameSelected = false;
  40. this.altKeyDown = false;
  41. this.controlKeyDown = false;
  42. this.shiftKeyDown = false;
  43. this.metaKeyDown = false;
  44. this.modalDialogTest = null;
  45. this.recordedAlerts = new Array();
  46. this.recordedConfirmations = new Array();
  47. this.recordedPrompts = new Array();
  48. this.openedWindows = {};
  49. this.nextConfirmResult = true;
  50. this.nextPromptResult = '';
  51. this.newPageLoaded = false;
  52. this.pageLoadError = null;
  53. this.shouldHighlightLocatedElement = false;
  54. this.uniqueId = "seleniumMarker" + new Date().getTime();
  55. this.pollingForLoad = new Object();
  56. this.permDeniedCount = new Object();
  57. this.windowPollers = new Array();
  58. // DGF for backwards compatibility
  59. this.browserbot = this;
  60. var self = this;
  61. objectExtend(this, PageBot.prototype);
  62. this._registerAllLocatorFunctions();
  63. this.recordPageLoad = function(elementOrWindow) {
  64. LOG.debug("Page load detected");
  65. try {
  66. if (elementOrWindow.location && elementOrWindow.location.href) {
  67. LOG.debug("Page load location=" + elementOrWindow.location.href);
  68. } else if (elementOrWindow.contentWindow && elementOrWindow.contentWindow.location && elementOrWindow.contentWindow.location.href) {
  69. LOG.debug("Page load location=" + elementOrWindow.contentWindow.location.href);
  70. } else {
  71. LOG.debug("Page load location unknown, current window location=" + this.getCurrentWindow(true).location);
  72. }
  73. } catch (e) {
  74. LOG.error("Caught an exception attempting to log location; this should get noticed soon!");
  75. LOG.exception(e);
  76. self.pageLoadError = e;
  77. return;
  78. }
  79. self.newPageLoaded = true;
  80. };
  81. this.isNewPageLoaded = function() {
  82. if (this.pageLoadError) {
  83. LOG.error("isNewPageLoaded found an old pageLoadError");
  84. var e = this.pageLoadError;
  85. this.pageLoadError = null;
  86. throw e;
  87. }
  88. return self.newPageLoaded;
  89. };
  90. };
  91. // DGF PageBot exists for backwards compatibility with old user-extensions
  92. var PageBot = function(){};
  93. BrowserBot.createForWindow = function(window, proxyInjectionMode) {
  94. var browserbot;
  95. LOG.debug('createForWindow');
  96. LOG.debug("browserName: " + browserVersion.name);
  97. LOG.debug("userAgent: " + navigator.userAgent);
  98. if (browserVersion.isIE) {
  99. browserbot = new IEBrowserBot(window);
  100. }
  101. else if (browserVersion.isKonqueror) {
  102. browserbot = new KonquerorBrowserBot(window);
  103. }
  104. else if (browserVersion.isOpera) {
  105. browserbot = new OperaBrowserBot(window);
  106. }
  107. else if (browserVersion.isSafari) {
  108. browserbot = new SafariBrowserBot(window);
  109. }
  110. else {
  111. // Use mozilla by default
  112. browserbot = new MozillaBrowserBot(window);
  113. }
  114. // getCurrentWindow has the side effect of modifying it to handle page loads etc
  115. browserbot.proxyInjectionMode = proxyInjectionMode;
  116. browserbot.getCurrentWindow(); // for modifyWindow side effect. This is not a transparent style
  117. return browserbot;
  118. };
  119. // todo: rename? This doesn't actually "do" anything.
  120. BrowserBot.prototype.doModalDialogTest = function(test) {
  121. this.modalDialogTest = test;
  122. };
  123. BrowserBot.prototype.cancelNextConfirmation = function(result) {
  124. this.nextConfirmResult = result;
  125. };
  126. BrowserBot.prototype.setNextPromptResult = function(result) {
  127. this.nextPromptResult = result;
  128. };
  129. BrowserBot.prototype.hasAlerts = function() {
  130. return (this.recordedAlerts.length > 0);
  131. };
  132. BrowserBot.prototype.relayBotToRC = function(s) {
  133. // DGF need to do this funny trick to see if we're in PI mode, because
  134. // "this" might be the window, rather than the browserbot (e.g. during window.alert)
  135. var piMode = this.proxyInjectionMode;
  136. if (!piMode) {
  137. if (typeof(selenium) != "undefined") {
  138. piMode = selenium.browserbot && selenium.browserbot.proxyInjectionMode;
  139. }
  140. }
  141. if (piMode) {
  142. this.relayToRC("selenium." + s);
  143. }
  144. };
  145. BrowserBot.prototype.relayToRC = function(name) {
  146. var object = eval(name);
  147. var s = 'state:' + serializeObject(name, object) + "\n";
  148. sendToRC(s,"state=true");
  149. }
  150. BrowserBot.prototype.resetPopups = function() {
  151. this.recordedAlerts = [];
  152. this.recordedConfirmations = [];
  153. this.recordedPrompts = [];
  154. }
  155. BrowserBot.prototype.getNextAlert = function() {
  156. var t = this.recordedAlerts.shift();
  157. if (t) {
  158. t = t.replace(/\n/g, " "); // because Selenese loses \n's when retrieving text from HTML table
  159. }
  160. this.relayBotToRC("browserbot.recordedAlerts");
  161. return t;
  162. };
  163. BrowserBot.prototype.hasConfirmations = function() {
  164. return (this.recordedConfirmations.length > 0);
  165. };
  166. BrowserBot.prototype.getNextConfirmation = function() {
  167. var t = this.recordedConfirmations.shift();
  168. this.relayBotToRC("browserbot.recordedConfirmations");
  169. return t;
  170. };
  171. BrowserBot.prototype.hasPrompts = function() {
  172. return (this.recordedPrompts.length > 0);
  173. };
  174. BrowserBot.prototype.getNextPrompt = function() {
  175. var t = this.recordedPrompts.shift();
  176. this.relayBotToRC("browserbot.recordedPrompts");
  177. return t;
  178. };
  179. /* Fire a mouse event in a browser-compatible manner */
  180. BrowserBot.prototype.triggerMouseEvent = function(element, eventType, canBubble, clientX, clientY, button) {
  181. clientX = clientX ? clientX : 0;
  182. clientY = clientY ? clientY : 0;
  183. LOG.debug("triggerMouseEvent assumes setting screenX and screenY to 0 is ok");
  184. var screenX = 0;
  185. var screenY = 0;
  186. canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
  187. if (element.fireEvent && element.ownerDocument && element.ownerDocument.createEventObject) { //IE
  188. var evt = createEventObject(element, this.controlKeyDown, this.altKeyDown, this.shiftKeyDown, this.metaKeyDown);
  189. evt.detail = 0;
  190. evt.button = button ? button : 1; // default will be the left mouse click ( http://www.javascriptkit.com/jsref/event.shtml )
  191. evt.relatedTarget = null;
  192. if (!screenX && !screenY && !clientX && !clientY && !this.controlKeyDown && !this.altKeyDown && !this.shiftKeyDown && !this.metaKeyDown) {
  193. element.fireEvent('on' + eventType);
  194. }
  195. else {
  196. evt.screenX = screenX;
  197. evt.screenY = screenY;
  198. evt.clientX = clientX;
  199. evt.clientY = clientY;
  200. // when we go this route, window.event is never set to contain the event we have just created.
  201. // ideally we could just slide it in as follows in the try-block below, but this normally
  202. // doesn't work. This is why I try to avoid this code path, which is only required if we need to
  203. // set attributes on the event (e.g., clientX).
  204. try {
  205. window.event = evt;
  206. }
  207. catch(e) {
  208. // getting an "Object does not support this action or property" error. Save the event away
  209. // for future reference.
  210. // TODO: is there a way to update window.event?
  211. // work around for http://jira.openqa.org/browse/SEL-280 -- make the event available somewhere:
  212. selenium.browserbot.getCurrentWindow().selenium_event = evt;
  213. }
  214. element.fireEvent('on' + eventType, evt);
  215. }
  216. }
  217. else {
  218. var evt = document.createEvent('MouseEvents');
  219. if (evt.initMouseEvent)
  220. {
  221. // see http://developer.mozilla.org/en/docs/DOM:event.button and
  222. // http://developer.mozilla.org/en/docs/DOM:event.initMouseEvent for button ternary logic logic
  223. //Safari
  224. evt.initMouseEvent(eventType, canBubble, true, document.defaultView, 1, screenX, screenY, clientX, clientY,
  225. this.controlKeyDown, this.altKeyDown, this.shiftKeyDown, this.metaKeyDown, button ? button : 0, null);
  226. }
  227. else {
  228. LOG.warn("element doesn't have initMouseEvent; firing an event which should -- but doesn't -- have other mouse-event related attributes here, as well as controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown");
  229. evt.initEvent(eventType, canBubble, true);
  230. evt.shiftKey = this.shiftKeyDown;
  231. evt.metaKey = this.metaKeyDown;
  232. evt.altKey = this.altKeyDown;
  233. evt.ctrlKey = this.controlKeyDown;
  234. if(button)
  235. {
  236. evt.button = button;
  237. }
  238. }
  239. element.dispatchEvent(evt);
  240. }
  241. }
  242. BrowserBot.prototype._windowClosed = function(win) {
  243. var c = win.closed;
  244. if (c == null) return true;
  245. return c;
  246. };
  247. BrowserBot.prototype._modifyWindow = function(win) {
  248. // In proxyInjectionMode, have to suppress LOG calls in _modifyWindow to avoid an infinite loop
  249. if (this._windowClosed(win)) {
  250. if (!this.proxyInjectionMode) {
  251. LOG.error("modifyWindow: Window was closed!");
  252. }
  253. return null;
  254. }
  255. if (!this.proxyInjectionMode) {
  256. LOG.debug('modifyWindow ' + this.uniqueId + ":" + win[this.uniqueId]);
  257. }
  258. if (!win[this.uniqueId]) {
  259. win[this.uniqueId] = 1;
  260. this.modifyWindowToRecordPopUpDialogs(win, this);
  261. }
  262. // In proxyInjection mode, we have our own mechanism for detecting page loads
  263. if (!this.proxyInjectionMode) {
  264. this.modifySeparateTestWindowToDetectPageLoads(win);
  265. }
  266. if (win.frames && win.frames.length && win.frames.length > 0) {
  267. for (var i = 0; i < win.frames.length; i++) {
  268. try {
  269. this._modifyWindow(win.frames[i]);
  270. } catch (e) {} // we're just trying to be opportunistic; don't worry if this doesn't work out
  271. }
  272. }
  273. return win;
  274. };
  275. BrowserBot.prototype.selectWindow = function(target) {
  276. if (!target || target == "null") {
  277. this._selectTopWindow();
  278. return;
  279. }
  280. var result = target.match(/^([a-zA-Z]+)=(.*)/);
  281. if (!result) {
  282. try {
  283. this._selectWindowByName(target);
  284. }
  285. catch (e) {
  286. this._selectWindowByTitle(target);
  287. }
  288. return;
  289. }
  290. locatorType = result[1];
  291. locatorValue = result[2];
  292. if (locatorType == "title") {
  293. this._selectWindowByTitle(locatorValue);
  294. }
  295. // TODO separate name and var into separate functions
  296. else if (locatorType == "name") {
  297. this._selectWindowByName(locatorValue);
  298. } else if (locatorType == "var") {
  299. this._selectWindowByName(locatorValue);
  300. } else {
  301. throw new SeleniumError("Window locator not recognized: " + locatorType);
  302. }
  303. };
  304. BrowserBot.prototype._selectTopWindow = function() {
  305. this.currentWindowName = null;
  306. this.currentWindow = this.topWindow;
  307. this.topFrame = this.topWindow;
  308. this.isSubFrameSelected = false;
  309. }
  310. BrowserBot.prototype._selectWindowByName = function(target) {
  311. this.currentWindow = this.getWindowByName(target, false);
  312. this.topFrame = this.currentWindow;
  313. this.currentWindowName = target;
  314. this.isSubFrameSelected = false;
  315. }
  316. BrowserBot.prototype._selectWindowByTitle = function(target) {
  317. var windowName = this.getWindowNameByTitle(target);
  318. if (!windowName) {
  319. this._selectTopWindow();
  320. } else {
  321. this._selectWindowByName(windowName);
  322. }
  323. }
  324. BrowserBot.prototype.selectFrame = function(target) {
  325. if (target.indexOf("index=") == 0) {
  326. target = target.substr(6);
  327. var frame = this.getCurrentWindow().frames[target];
  328. if (frame == null) {
  329. throw new SeleniumError("Not found: frames["+index+"]");
  330. }
  331. if (!frame.document) {
  332. throw new SeleniumError("frames["+index+"] is not a frame");
  333. }
  334. this.currentWindow = frame;
  335. this.isSubFrameSelected = true;
  336. }
  337. else if (target == "relative=up" || target == "relative=parent") {
  338. this.currentWindow = this.getCurrentWindow().parent;
  339. this.isSubFrameSelected = (this._getFrameElement(this.currentWindow) != null);
  340. } else if (target == "relative=top") {
  341. this.currentWindow = this.topFrame;
  342. this.isSubFrameSelected = false;
  343. } else {
  344. var frame = this.findElement(target);
  345. if (frame == null) {
  346. throw new SeleniumError("Not found: " + target);
  347. }
  348. // now, did they give us a frame or a frame ELEMENT?
  349. var match = false;
  350. if (frame.contentWindow) {
  351. // this must be a frame element
  352. if (browserVersion.isHTA) {
  353. // stupid HTA bug; can't get in the front door
  354. target = frame.contentWindow.name;
  355. } else {
  356. this.currentWindow = frame.contentWindow;
  357. this.isSubFrameSelected = true;
  358. match = true;
  359. }
  360. } else if (frame.document && frame.location) {
  361. // must be an actual window frame
  362. this.currentWindow = frame;
  363. this.isSubFrameSelected = true;
  364. match = true;
  365. }
  366. if (!match) {
  367. // neither, let's loop through the frame names
  368. var win = this.getCurrentWindow();
  369. if (win && win.frames && win.frames.length) {
  370. for (var i = 0; i < win.frames.length; i++) {
  371. if (win.frames[i].name == target) {
  372. this.currentWindow = win.frames[i];
  373. this.isSubFrameSelected = true;
  374. match = true;
  375. break;
  376. }
  377. }
  378. }
  379. if (!match) {
  380. throw new SeleniumError("Not a frame: " + target);
  381. }
  382. }
  383. }
  384. // modifies the window
  385. this.getCurrentWindow();
  386. };
  387. BrowserBot.prototype.doesThisFrameMatchFrameExpression = function(currentFrameString, target) {
  388. var isDom = false;
  389. if (target.indexOf("dom=") == 0) {
  390. target = target.substr(4);
  391. isDom = true;
  392. } else if (target.indexOf("index=") == 0) {
  393. target = "frames[" + target.substr(6) + "]";
  394. isDom = true;
  395. }
  396. var t;
  397. try {
  398. eval("t=" + currentFrameString + "." + target);
  399. } catch (e) {
  400. }
  401. var autWindow = this.browserbot.getCurrentWindow();
  402. if (t != null) {
  403. try {
  404. if (t.window == autWindow) {
  405. return true;
  406. }
  407. if (t.window.uniqueId == autWindow.uniqueId) {
  408. return true;
  409. }
  410. return false;
  411. } catch (permDenied) {
  412. // DGF if the windows are incomparable, they're probably not the same...
  413. }
  414. }
  415. if (isDom) {
  416. return false;
  417. }
  418. var currentFrame;
  419. eval("currentFrame=" + currentFrameString);
  420. if (target == "relative=up") {
  421. if (currentFrame.window.parent == autWindow) {
  422. return true;
  423. }
  424. return false;
  425. }
  426. if (target == "relative=top") {
  427. if (currentFrame.window.top == autWindow) {
  428. return true;
  429. }
  430. return false;
  431. }
  432. if (currentFrame.window == autWindow.parent) {
  433. if (autWindow.name == target) {
  434. return true;
  435. }
  436. try {
  437. var element = this.findElement(target, currentFrame.window);
  438. if (element.contentWindow == autWindow) {
  439. return true;
  440. }
  441. } catch (e) {}
  442. }
  443. return false;
  444. };
  445. BrowserBot.prototype.openLocation = function(target) {
  446. // We're moving to a new page - clear the current one
  447. var win = this.getCurrentWindow();
  448. LOG.debug("openLocation newPageLoaded = false");
  449. this.newPageLoaded = false;
  450. this.setOpenLocation(win, target);
  451. };
  452. BrowserBot.prototype.openWindow = function(url, windowID) {
  453. if (url != "") {
  454. url = absolutify(url, this.baseUrl);
  455. }
  456. if (browserVersion.isHTA) {
  457. // in HTA mode, calling .open on the window interprets the url relative to that window
  458. // we need to absolute-ize the URL to make it consistent
  459. var child = this.getCurrentWindow().open(url, windowID);
  460. selenium.browserbot.openedWindows[windowID] = child;
  461. } else {
  462. this.getCurrentWindow().open(url, windowID);
  463. }
  464. };
  465. BrowserBot.prototype.setIFrameLocation = function(iframe, location) {
  466. iframe.src = location;
  467. };
  468. BrowserBot.prototype.setOpenLocation = function(win, loc) {
  469. loc = absolutify(loc, this.baseUrl);
  470. if (browserVersion.isHTA) {
  471. var oldHref = win.location.href;
  472. win.location.href = loc;
  473. var marker = null;
  474. try {
  475. marker = this.isPollingForLoad(win);
  476. if (marker && win.location[marker]) {
  477. win.location[marker] = false;
  478. }
  479. } catch (e) {} // DGF don't know why, but this often fails
  480. } else {
  481. win.location.href = loc;
  482. }
  483. };
  484. BrowserBot.prototype.getCurrentPage = function() {
  485. return this;
  486. };
  487. BrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
  488. var self = this;
  489. windowToModify.seleniumAlert = windowToModify.alert;
  490. windowToModify.alert = function(alert) {
  491. browserBot.recordedAlerts.push(alert);
  492. self.relayBotToRC.call(self, "browserbot.recordedAlerts");
  493. };
  494. windowToModify.confirm = function(message) {
  495. browserBot.recordedConfirmations.push(message);
  496. var result = browserBot.nextConfirmResult;
  497. browserBot.nextConfirmResult = true;
  498. self.relayBotToRC.call(self, "browserbot.recordedConfirmations");
  499. return result;
  500. };
  501. windowToModify.prompt = function(message) {
  502. browserBot.recordedPrompts.push(message);
  503. var result = !browserBot.nextConfirmResult ? null : browserBot.nextPromptResult;
  504. browserBot.nextConfirmResult = true;
  505. browserBot.nextPromptResult = '';
  506. self.relayBotToRC.call(self, "browserbot.recordedPrompts");
  507. return result;
  508. };
  509. // Keep a reference to all popup windows by name
  510. // note that in IE the "windowName" argument must be a valid javascript identifier, it seems.
  511. var originalOpen = windowToModify.open;
  512. var originalOpenReference;
  513. if (browserVersion.isHTA) {
  514. originalOpenReference = 'selenium_originalOpen' + new Date().getTime();
  515. windowToModify[originalOpenReference] = windowToModify.open;
  516. }
  517. var isHTA = browserVersion.isHTA;
  518. var newOpen = function(url, windowName, windowFeatures, replaceFlag) {
  519. var myOriginalOpen = originalOpen;
  520. if (isHTA) {
  521. myOriginalOpen = this[originalOpenReference];
  522. }
  523. if (windowName == "" || windowName == "_blank") {
  524. windowName = "selenium_blank" + Math.round(100000 * Math.random());
  525. LOG.warn("Opening window '_blank', which is not a real window name. Randomizing target to be: " + windowName);
  526. }
  527. var openedWindow = myOriginalOpen(url, windowName, windowFeatures, replaceFlag);
  528. LOG.debug("window.open call intercepted; window ID (which you can use with selectWindow()) is \"" + windowName + "\"");
  529. if (windowName!=null) {
  530. openedWindow["seleniumWindowName"] = windowName;
  531. }
  532. selenium.browserbot.openedWindows[windowName] = openedWindow;
  533. return openedWindow;
  534. };
  535. if (browserVersion.isHTA) {
  536. originalOpenReference = 'selenium_originalOpen' + new Date().getTime();
  537. newOpenReference = 'selenium_newOpen' + new Date().getTime();
  538. var setOriginalRef = "this['" + originalOpenReference + "'] = this.open;";
  539. if (windowToModify.eval) {
  540. windowToModify.eval(setOriginalRef);
  541. windowToModify.open = newOpen;
  542. } else {
  543. // DGF why can't I eval here? Seems like I'm querying the window at a bad time, maybe?
  544. setOriginalRef += "this.open = this['" + newOpenReference + "'];";
  545. windowToModify[newOpenReference] = newOpen;
  546. windowToModify.setTimeout(setOriginalRef, 0);
  547. }
  548. } else {
  549. windowToModify.open = newOpen;
  550. }
  551. };
  552. /**
  553. * Call the supplied function when a the current page unloads and a new one loads.
  554. * This is done by polling continuously until the document changes and is fully loaded.
  555. */
  556. BrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads = function(windowObject) {
  557. // Since the unload event doesn't fire in Safari 1.3, we start polling immediately
  558. if (!windowObject) {
  559. LOG.warn("modifySeparateTestWindowToDetectPageLoads: no windowObject!");
  560. return;
  561. }
  562. if (this._windowClosed(windowObject)) {
  563. LOG.info("modifySeparateTestWindowToDetectPageLoads: windowObject was closed");
  564. return;
  565. }
  566. var oldMarker = this.isPollingForLoad(windowObject);
  567. if (oldMarker) {
  568. LOG.debug("modifySeparateTestWindowToDetectPageLoads: already polling this window: " + oldMarker);
  569. return;
  570. }
  571. var marker = 'selenium' + new Date().getTime();
  572. LOG.debug("Starting pollForLoad (" + marker + "): " + windowObject.location);
  573. this.pollingForLoad[marker] = true;
  574. // if this is a frame, add a load listener, otherwise, attach a poller
  575. var frameElement = this._getFrameElement(windowObject);
  576. // DGF HTA mode can't attach load listeners to subframes (yuk!)
  577. var htaSubFrame = this._isHTASubFrame(windowObject);
  578. if (frameElement && !htaSubFrame) {
  579. LOG.debug("modifySeparateTestWindowToDetectPageLoads: this window is a frame; attaching a load listener");
  580. addLoadListener(frameElement, this.recordPageLoad);
  581. frameElement[marker] = true;
  582. frameElement["frame"+this.uniqueId] = marker;
  583. LOG.debug("dgf this.uniqueId="+this.uniqueId);
  584. LOG.debug("dgf marker="+marker);
  585. LOG.debug("dgf frameElement['frame'+this.uniqueId]="+frameElement['frame'+this.uniqueId]);
  586. frameElement[this.uniqueId] = marker;
  587. LOG.debug("dgf frameElement[this.uniqueId]="+frameElement[this.uniqueId]);
  588. } else {
  589. windowObject.location[marker] = true;
  590. windowObject[this.uniqueId] = marker;
  591. this.pollForLoad(this.recordPageLoad, windowObject, windowObject.document, windowObject.location, windowObject.location.href, marker);
  592. }
  593. };
  594. BrowserBot.prototype._isHTASubFrame = function(win) {
  595. if (!browserVersion.isHTA) return false;
  596. // DGF this is wrong! what if "win" isn't the selected window?
  597. return this.isSubFrameSelected;
  598. }
  599. BrowserBot.prototype._getFrameElement = function(win) {
  600. var frameElement = null;
  601. var caught;
  602. try {
  603. frameElement = win.frameElement;
  604. } catch (e) {
  605. caught = true;
  606. }
  607. if (caught) {
  608. // on IE, checking frameElement in a pop-up results in a "No such interface supported" exception
  609. // but it might have a frame element anyway!
  610. var parentContainsIdenticallyNamedFrame = false;
  611. try {
  612. parentContainsIdenticallyNamedFrame = win.parent.frames[win.name];
  613. } catch (e) {} // this may fail if access is denied to the parent; in that case, assume it's not a pop-up
  614. if (parentContainsIdenticallyNamedFrame) {
  615. // it can't be a coincidence that the parent has a frame with the same name as myself!
  616. var result;
  617. try {
  618. result = parentContainsIdenticallyNamedFrame.frameElement;
  619. if (result) {
  620. return result;
  621. }
  622. } catch (e) {} // it was worth a try! _getFrameElementsByName is often slow
  623. result = this._getFrameElementByName(win.name, win.parent.document, win);
  624. return result;
  625. }
  626. }
  627. LOG.debug("_getFrameElement: frameElement="+frameElement);
  628. if (frameElement) {
  629. LOG.debug("frameElement.name="+frameElement.name);
  630. }
  631. return frameElement;
  632. }
  633. BrowserBot.prototype._getFrameElementByName = function(name, doc, win) {
  634. var frames;
  635. var frame;
  636. var i;
  637. frames = doc.getElementsByTagName("iframe");
  638. for (i = 0; i < frames.length; i++) {
  639. frame = frames[i];
  640. if (frame.name === name) {
  641. return frame;
  642. }
  643. }
  644. frames = doc.getElementsByTagName("frame");
  645. for (i = 0; i < frames.length; i++) {
  646. frame = frames[i];
  647. if (frame.name === name) {
  648. return frame;
  649. }
  650. }
  651. // DGF weird; we only call this function when we know the doc contains the frame
  652. LOG.warn("_getFrameElementByName couldn't find a frame or iframe; checking every element for the name " + name);
  653. return BrowserBot.prototype.locateElementByName(win.name, win.parent.document);
  654. }
  655. /**
  656. * Set up a polling timer that will keep checking the readyState of the document until it's complete.
  657. * Since we might call this before the original page is unloaded, we first check to see that the current location
  658. * or href is different from the original one.
  659. */
  660. BrowserBot.prototype.pollForLoad = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
  661. LOG.debug("pollForLoad original (" + marker + "): " + originalHref);
  662. try {
  663. if (this._windowClosed(windowObject)) {
  664. LOG.debug("pollForLoad WINDOW CLOSED (" + marker + ")");
  665. delete this.pollingForLoad[marker];
  666. return;
  667. }
  668. var isSamePage = this._isSamePage(windowObject, originalDocument, originalLocation, originalHref, marker);
  669. var rs = this.getReadyState(windowObject, windowObject.document);
  670. if (!isSamePage && rs == 'complete') {
  671. var currentHref = windowObject.location.href;
  672. LOG.debug("pollForLoad FINISHED (" + marker + "): " + rs + " (" + currentHref + ")");
  673. delete this.pollingForLoad[marker];
  674. this._modifyWindow(windowObject);
  675. var newMarker = this.isPollingForLoad(windowObject);
  676. if (!newMarker) {
  677. LOG.debug("modifyWindow didn't start new poller: " + newMarker);
  678. this.modifySeparateTestWindowToDetectPageLoads(windowObject);
  679. }
  680. newMarker = this.isPollingForLoad(windowObject);
  681. var currentlySelectedWindow;
  682. var currentlySelectedWindowMarker;
  683. currentlySelectedWindow =this.getCurrentWindow(true);
  684. currentlySelectedWindowMarker = currentlySelectedWindow[this.uniqueId];
  685. LOG.debug("pollForLoad (" + marker + ") restarting " + newMarker);
  686. if (/(TestRunner-splash|Blank)\.html\?start=true$/.test(currentHref)) {
  687. LOG.debug("pollForLoad Oh, it's just the starting page. Never mind!");
  688. } else if (currentlySelectedWindowMarker == newMarker) {
  689. loadFunction(currentlySelectedWindow);
  690. } else {
  691. LOG.debug("pollForLoad page load detected in non-current window; ignoring (currentlySelected="+currentlySelectedWindowMarker+", detection in "+newMarker+")");
  692. }
  693. return;
  694. }
  695. LOG.debug("pollForLoad continue (" + marker + "): " + currentHref);
  696. this.reschedulePoller(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
  697. } catch (e) {
  698. LOG.debug("Exception during pollForLoad; this should get noticed soon (" + e.message + ")!");
  699. //DGF this is supposed to get logged later; log it at debug just in case
  700. //LOG.exception(e);
  701. this.pageLoadError = e;
  702. }
  703. };
  704. BrowserBot.prototype._isSamePage = function(windowObject, originalDocument, originalLocation, originalHref, marker) {
  705. var currentDocument = windowObject.document;
  706. var currentLocation = windowObject.location;
  707. var currentHref = currentLocation.href
  708. var sameDoc = this._isSameDocument(originalDocument, currentDocument);
  709. var sameLoc = (originalLocation === currentLocation);
  710. // hash marks don't meant the page has loaded, so we need to strip them off if they exist...
  711. var currentHash = currentHref.indexOf('#');
  712. if (currentHash > 0) {
  713. currentHref = currentHref.substring(0, currentHash);
  714. }
  715. var originalHash = originalHref.indexOf('#');
  716. if (originalHash > 0) {
  717. originalHref = originalHref.substring(0, originalHash);
  718. }
  719. LOG.debug("_isSamePage: currentHref: " + currentHref);
  720. LOG.debug("_isSamePage: originalHref: " + originalHref);
  721. var sameHref = (originalHref === currentHref);
  722. var markedLoc = currentLocation[marker];
  723. if (browserVersion.isKonqueror || browserVersion.isSafari) {
  724. // the mark disappears too early on these browsers
  725. markedLoc = true;
  726. }
  727. // since this is some _very_ important logic, especially for PI and multiWindow mode, we should log all these out
  728. LOG.debug("_isSamePage: sameDoc: " + sameDoc);
  729. LOG.debug("_isSamePage: sameLoc: " + sameLoc);
  730. LOG.debug("_isSamePage: sameHref: " + sameHref);
  731. LOG.debug("_isSamePage: markedLoc: " + markedLoc);
  732. return sameDoc && sameLoc && sameHref && markedLoc
  733. };
  734. BrowserBot.prototype._isSameDocument = function(originalDocument, currentDocument) {
  735. return originalDocument === currentDocument;
  736. };
  737. BrowserBot.prototype.getReadyState = function(windowObject, currentDocument) {
  738. var rs = currentDocument.readyState;
  739. if (rs == null) {
  740. if ((this.buttonWindow!=null && this.buttonWindow.document.readyState == null) // not proxy injection mode (and therefore buttonWindow isn't null)
  741. || (top.document.readyState == null)) { // proxy injection mode (and therefore everything's in the top window, but buttonWindow doesn't exist)
  742. // uh oh! we're probably on Firefox with no readyState extension installed!
  743. // We'll have to just take a guess as to when the document is loaded; this guess
  744. // will never be perfect. :-(
  745. if (typeof currentDocument.getElementsByTagName != 'undefined'
  746. && typeof currentDocument.getElementById != 'undefined'
  747. && ( currentDocument.getElementsByTagName('body')[0] != null
  748. || currentDocument.body != null )) {
  749. if (windowObject.frameElement && windowObject.location.href == "about:blank" && windowObject.frameElement.src != "about:blank") {
  750. LOG.info("getReadyState not loaded, frame location was about:blank, but frame src = " + windowObject.frameElement.src);
  751. return null;
  752. }
  753. LOG.debug("getReadyState = windowObject.frames.length = " + windowObject.frames.length);
  754. for (var i = 0; i < windowObject.frames.length; i++) {
  755. LOG.debug("i = " + i);
  756. if (this.getReadyState(windowObject.frames[i], windowObject.frames[i].document) != 'complete') {
  757. LOG.debug("getReadyState aha! the nested frame " + windowObject.frames[i].name + " wasn't ready!");
  758. return null;
  759. }
  760. }
  761. rs = 'complete';
  762. } else {
  763. LOG.debug("pollForLoad readyState was null and DOM appeared to not be ready yet");
  764. }
  765. }
  766. }
  767. else if (rs == "loading" && browserVersion.isIE) {
  768. LOG.debug("pageUnloading = true!!!!");
  769. this.pageUnloading = true;
  770. }
  771. LOG.debug("getReadyState returning " + rs);
  772. return rs;
  773. };
  774. /** This function isn't used normally, but was the way we used to schedule pollers:
  775. asynchronously executed autonomous units. This is deprecated, but remains here
  776. for future reference.
  777. */
  778. BrowserBot.prototype.XXXreschedulePoller = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
  779. var self = this;
  780. window.setTimeout(function() {
  781. self.pollForLoad(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
  782. }, 500);
  783. };
  784. /** This function isn't used normally, but is useful for debugging asynchronous pollers
  785. * To enable it, rename it to "reschedulePoller", so it will override the
  786. * existing reschedulePoller function
  787. */
  788. BrowserBot.prototype.XXXreschedulePoller = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
  789. var doc = this.buttonWindow.document;
  790. var button = doc.createElement("button");
  791. var buttonName = doc.createTextNode(marker + " - " + windowObject.name);
  792. button.appendChild(buttonName);
  793. var tools = doc.getElementById("tools");
  794. var self = this;
  795. button.onclick = function() {
  796. tools.removeChild(button);
  797. self.pollForLoad(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
  798. };
  799. tools.appendChild(button);
  800. window.setTimeout(button.onclick, 500);
  801. };
  802. BrowserBot.prototype.reschedulePoller = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
  803. var self = this;
  804. var pollerFunction = function() {
  805. self.pollForLoad(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
  806. };
  807. this.windowPollers.push(pollerFunction);
  808. };
  809. BrowserBot.prototype.runScheduledPollers = function() {
  810. LOG.debug("runScheduledPollers");
  811. var oldPollers = this.windowPollers;
  812. this.windowPollers = new Array();
  813. for (var i = 0; i < oldPollers.length; i++) {
  814. oldPollers[i].call();
  815. }
  816. LOG.debug("runScheduledPollers DONE");
  817. };
  818. BrowserBot.prototype.isPollingForLoad = function(win) {
  819. var marker;
  820. var frameElement = this._getFrameElement(win);
  821. var htaSubFrame = this._isHTASubFrame(win);
  822. if (frameElement && !htaSubFrame) {
  823. marker = frameElement["frame"+this.uniqueId];
  824. } else {
  825. marker = win[this.uniqueId];
  826. }
  827. if (!marker) {
  828. LOG.debug("isPollingForLoad false, missing uniqueId " + this.uniqueId + ": " + marker);
  829. return false;
  830. }
  831. if (!this.pollingForLoad[marker]) {
  832. LOG.debug("isPollingForLoad false, this.pollingForLoad[" + marker + "]: " + this.pollingForLoad[marker]);
  833. return false;
  834. }
  835. return marker;
  836. };
  837. BrowserBot.prototype.getWindowByName = function(windowName, doNotModify) {
  838. LOG.debug("getWindowByName(" + windowName + ")");
  839. // First look in the map of opened windows
  840. var targetWindow = this.openedWindows[windowName];
  841. if (!targetWindow) {
  842. targetWindow = this.topWindow[windowName];
  843. }
  844. if (!targetWindow && windowName == "_blank") {
  845. for (var winName in this.openedWindows) {
  846. // _blank can match selenium_blank*, if it looks like it's OK (valid href, not closed)
  847. if (/^selenium_blank/.test(winName)) {
  848. targetWindow = this.openedWindows[winName];
  849. var ok;
  850. try {
  851. if (!this._windowClosed(targetWindow)) {
  852. ok = targetWindow.location.href;
  853. }
  854. } catch (e) {}
  855. if (ok) break;
  856. }
  857. }
  858. }
  859. if (!targetWindow) {
  860. throw new SeleniumError("Window does not exist. If this looks like a Selenium bug, make sure to read http://selenium-core.openqa.org/reference.html#openWindow for potential workarounds.");
  861. }
  862. if (browserVersion.isHTA) {
  863. try {
  864. targetWindow.location.href;
  865. } catch (e) {
  866. targetWindow = window.open("", targetWindow.name);
  867. this.openedWindows[targetWindow.name] = targetWindow;
  868. }
  869. }
  870. if (!doNotModify) {
  871. this._modifyWindow(targetWindow);
  872. }
  873. return targetWindow;
  874. };
  875. /**
  876. * Find a window name from the window title.
  877. */
  878. BrowserBot.prototype.getWindowNameByTitle = function(windowTitle) {
  879. LOG.debug("getWindowNameByTitle(" + windowTitle + ")");
  880. // First look in the map of opened windows and iterate them
  881. for (var windowName in this.openedWindows) {
  882. var targetWindow = this.openedWindows[windowName];
  883. // If the target window's title is our title
  884. try {
  885. // TODO implement Pattern Matching here
  886. if (!this._windowClosed(targetWindow) &&
  887. targetWindow.document.title == windowTitle) {
  888. return windowName;
  889. }
  890. } catch (e) {
  891. // You'll often get Permission Denied errors here in IE
  892. // eh, if we can't read this window's title,
  893. // it's probably not available to us right now anyway
  894. }
  895. }
  896. try {
  897. if (this.topWindow.document.title == windowTitle) {
  898. return "";
  899. }
  900. } catch (e) {} // IE Perm denied
  901. throw new SeleniumError("Could not find window with title " + windowTitle);
  902. };
  903. BrowserBot.prototype.getCurrentWindow = function(doNotModify) {
  904. if (this.proxyInjectionMode) {
  905. return window;
  906. }
  907. var testWindow = this.currentWindow;
  908. if (!doNotModify) {
  909. this._modifyWindow(testWindow);
  910. LOG.debug("getCurrentWindow newPageLoaded = false");
  911. this.newPageLoaded = false;
  912. }
  913. testWindow = this._handleClosedSubFrame(testWindow, doNotModify);
  914. return testWindow;
  915. };
  916. BrowserBot.prototype._handleClosedSubFrame = function(testWindow, doNotModify) {
  917. if (this.proxyInjectionMode) {
  918. return testWindow;
  919. }
  920. if (this.isSubFrameSelected) {
  921. var missing = true;
  922. if (testWindow.parent && testWindow.parent.frames && testWindow.parent.frames.length) {
  923. for (var i = 0; i < testWindow.parent.frames.length; i++) {
  924. if (testWindow.parent.frames[i] == testWindow) {
  925. missing = false;
  926. break;
  927. }
  928. }
  929. }
  930. if (missing) {
  931. LOG.warn("Current subframe appears to have closed; selecting top frame");
  932. this.selectFrame("relative=top");
  933. return this.getCurrentWindow(doNotModify);
  934. }
  935. } else if (this._windowClosed(testWindow)) {
  936. var closedError = new SeleniumError("Current window or frame is closed!");
  937. closedError.windowClosed = true;
  938. throw closedError;
  939. }
  940. return testWindow;
  941. };
  942. BrowserBot.prototype.highlight = function (element, force) {
  943. if (force || this.shouldHighlightLocatedElement) {
  944. try {
  945. highlight(element);
  946. } catch (e) {} // DGF element highlighting is low-priority and possibly dangerous
  947. }
  948. return element;
  949. }
  950. BrowserBot.prototype.setShouldHighlightElement = function (shouldHighlight) {
  951. this.shouldHighlightLocatedElement = shouldHighlight;
  952. }
  953. /*****************************************************************/
  954. /* BROWSER-SPECIFIC FUNCTIONS ONLY AFTER THIS LINE */
  955. BrowserBot.prototype._registerAllLocatorFunctions = function() {
  956. // TODO - don't do this in the constructor - only needed once ever
  957. this.locationStrategies = {};
  958. for (var functionName in this) {
  959. var result = /^locateElementBy([A-Z].+)$/.exec(functionName);
  960. if (result != null) {
  961. var locatorFunction = this[functionName];
  962. if (typeof(locatorFunction) != 'function') {
  963. continue;
  964. }
  965. // Use a specified prefix in preference to one generated from
  966. // the function name
  967. var locatorPrefix = locatorFunction.prefix || result[1].toLowerCase();
  968. this.locationStrategies[locatorPrefix] = locatorFunction;
  969. }
  970. }
  971. /**
  972. * Find a locator based on a prefix.
  973. */
  974. this.findElementBy = function(locatorType, locator, inDocument, inWindow) {
  975. var locatorFunction = this.locationStrategies[locatorType];
  976. if (! locatorFunction) {
  977. throw new SeleniumError("Unrecognised locator type: '" + locatorType + "'");
  978. }
  979. return locatorFunction.call(this, locator, inDocument, inWindow);
  980. };
  981. /**
  982. * The implicit locator, that is used when no prefix is supplied.
  983. */
  984. this.locationStrategies['implicit'] = function(locator, inDocument, inWindow) {
  985. if (locator.startsWith('//')) {
  986. return this.locateElementByXPath(locator, inDocument, inWindow);
  987. }
  988. if (locator.startsWith('document.')) {
  989. return this.locateElementByDomTraversal(locator, inDocument, inWindow);
  990. }
  991. return this.locateElementByIdentifier(locator, inDocument, inWindow);
  992. };
  993. }
  994. BrowserBot.prototype.getDocument = function() {
  995. return this.getCurrentWindow().document;
  996. }
  997. BrowserBot.prototype.getTitle = function() {
  998. var t = this.getDocument().title;
  999. if (typeof(t) == "string") {
  1000. t = t.trim();
  1001. }
  1002. return t;
  1003. }
  1004. BrowserBot.prototype.getCookieByName = function(cookieName, doc) {
  1005. if (!doc) doc = this.getDocument();
  1006. var ck = doc.cookie;
  1007. if (!ck) return null;
  1008. var ckPairs = ck.split(/;/);
  1009. for (var i = 0; i < ckPairs.length; i++) {
  1010. var ckPair = ckPairs[i].trim();
  1011. var ckNameValue = ckPair.split(/=/);
  1012. var ckName = decodeURIComponent(ckNameValue[0]);
  1013. if (ckName === cookieName) {
  1014. return decodeURIComponent(ckNameValue[1]);
  1015. }
  1016. }
  1017. return null;
  1018. }
  1019. BrowserBot.prototype.getAllCookieNames = function(doc) {
  1020. if (!doc) doc = this.getDocument();
  1021. var ck = doc.cookie;
  1022. if (!ck) return [];
  1023. var cookieNames = [];
  1024. var ckPairs = ck.split(/;/);
  1025. for (var i = 0; i < ckPairs.length; i++) {
  1026. var ckPair = ckPairs[i].trim();
  1027. var ckNameValue = ckPair.split(/=/);
  1028. var ckName = decodeURIComponent(ckNameValue[0]);
  1029. cookieNames.push(ckName);
  1030. }
  1031. return cookieNames;
  1032. }
  1033. BrowserBot.prototype.deleteCookie = function(cookieName, domain, path, doc) {
  1034. if (!doc) doc = this.getDocument();
  1035. var expireDateInMilliseconds = (new Date()).getTime() + (-1 * 1000);
  1036. var cookie = cookieName + "=deleted; ";
  1037. if (path) {
  1038. cookie += "path=" + path + "; ";
  1039. }
  1040. if (domain) {
  1041. cookie += "domain=" + domain + "; ";
  1042. }
  1043. cookie += "expires=" + new Date(expireDateInMilliseconds).toGMTString();
  1044. LOG.debug("Setting cookie to: " + cookie);
  1045. doc.cookie = cookie;
  1046. }
  1047. /** Try to delete cookie, return false if it didn't work */
  1048. BrowserBot.prototype._maybeDeleteCookie = function(cookieName, domain, path, doc) {
  1049. this.deleteCookie(cookieName, domain, path, doc);
  1050. return (!this.getCookieByName(cookieName, doc));
  1051. }
  1052. BrowserBot.prototype._recursivelyDeleteCookieDomains = function(cookieName, domain, path, doc) {
  1053. var deleted = this._maybeDeleteCookie(cookieName, domain, path, doc);
  1054. if (deleted) return true;
  1055. var dotIndex = domain.indexOf(".");
  1056. if (dotIndex == 0) {
  1057. return this._recursivelyDeleteCookieDomains(cookieName, domain.substring(1), path, doc);
  1058. } else if (dotIndex != -1) {
  1059. return this._recursivelyDeleteCookieDomains(cookieName, domain.substring(dotIndex), path, doc);
  1060. } else {
  1061. // No more dots; try just not passing in a domain at all
  1062. return this._maybeDeleteCookie(cookieName, null, path, doc);
  1063. }
  1064. }
  1065. BrowserBot.prototype._recursivelyDeleteCookie = function(cookieName, domain, path, doc) {
  1066. var slashIndex = path.lastIndexOf("/");
  1067. var finalIndex = path.length-1;
  1068. if (slashIndex == finalIndex) {
  1069. slashIndex--;
  1070. }
  1071. if (slashIndex != -1) {
  1072. deleted = this._recursivelyDeleteCookie(cookieName, domain, path.substring(0, slashIndex+1), doc);
  1073. if (deleted) return true;
  1074. }
  1075. return this._recursivelyDeleteCookieDomains(cookieName, domain, path, doc);
  1076. }
  1077. BrowserBot.prototype.recursivelyDeleteCookie = function(cookieName, domain, path, win) {
  1078. if (!win) win = this.getCurrentWindow();
  1079. var doc = win.document;
  1080. if (!domain) {
  1081. domain = doc.domain;
  1082. }
  1083. if (!path) {
  1084. path = win.location.pathname;
  1085. }
  1086. var deleted = this._recursivelyDeleteCookie(cookieName, "." + domain, path, doc);
  1087. if (deleted) return;
  1088. // Finally try a null path (Try it last because it's uncommon)
  1089. deleted = this._recursivelyDeleteCookieDomains(cookieName, "." + domain, null, doc);
  1090. if (deleted) return;
  1091. throw new SeleniumError("Couldn't delete cookie " + cookieName);
  1092. }
  1093. /*
  1094. * Finds an element recursively in frames and nested frames
  1095. * in the specified document, using various lookup protocols
  1096. */
  1097. BrowserBot.prototype.findElementRecursive = function(locatorType, locatorString, inDocument, inWindow) {
  1098. var element = this.findElementBy(locatorType, locatorString, inDocument, inWindow);
  1099. if (element != null) {
  1100. return element;
  1101. }
  1102. for (var i = 0; i < inWindow.frames.length; i++) {
  1103. // On some browsers, the document object is undefined for third-party
  1104. // frames. Make sure the document is valid before continuing.
  1105. if (inWindow.frames[i].document) {
  1106. element = this.findElementRecursive(locatorType, locatorString, inWindow.frames[i].document, inWindow.frames[i]);
  1107. if (element != null) {
  1108. return element;
  1109. }
  1110. }
  1111. }
  1112. };
  1113. /*
  1114. * Finds an element on the current page, using various lookup protocols
  1115. */
  1116. BrowserBot.prototype.findElementOrNull = function(locator, win) {
  1117. locator = parse_locator(locator);
  1118. if (win == null) {
  1119. win = this.getCurrentWindow();
  1120. }
  1121. var element = this.findElementRecursive(locator.type, locator.string, win.document, win);
  1122. if (element != null) {
  1123. return this.browserbot.highlight(element);
  1124. }
  1125. // Element was not found by any locator function.
  1126. return null;
  1127. };
  1128. BrowserBot.prototype.findElement = function(locator, win) {
  1129. var element = this.findElementOrNull(locator, win);
  1130. if (element == null) throw new SeleniumError("Element " + locator + " not found");
  1131. return element;
  1132. }
  1133. /**
  1134. * In non-IE browsers, getElementById() does not search by name. Instead, we
  1135. * we search separately by id and name.
  1136. */
  1137. BrowserBot.prototype.locateElementByIdentifier = function(identifier, inDocument, inWindow) {
  1138. return BrowserBot.prototype.locateElementById(identifier, inDocument, inWindow)
  1139. || BrowserBot.prototype.locateElementByName(identifier, inDocument, inWindow)
  1140. || null;
  1141. };
  1142. /**
  1143. * Find the element with id - can't rely on getElementById, coz it returns by name as well in IE..
  1144. */
  1145. BrowserBot.prototype.locateElementById = function(identifier, inDocument, inWindow) {
  1146. var element = inDocument.getElementById(identifier);
  1147. if (element && element.id === identifier) {
  1148. return element;
  1149. }
  1150. else if (browserVersion.isIE || browserVersion.isOpera) {
  1151. // SEL-484
  1152. var xpath = '/descendant::*[@id=' + identifier.quoteForXPath() + ']';
  1153. return BrowserBot.prototype
  1154. .locateElementByXPath(xpath, inDocument, inWindow);
  1155. }
  1156. else {
  1157. return null;
  1158. }
  1159. };
  1160. /**
  1161. * Find an element by name, refined by (optional) element-filter
  1162. * expressions.
  1163. */
  1164. BrowserBot.prototype.locateElementByName = function(locator, document, inWindow) {
  1165. var elements = document.getElementsByTagName("*");
  1166. var filters = locator.split(' ');
  1167. filters[0] = 'name=' + filters[0];
  1168. while (filters.length) {
  1169. var filter = filters.shift();
  1170. elements = this.selectElements(filter, elements, 'value');
  1171. }
  1172. if (elements.length > 0) {
  1173. return elements[0];
  1174. }
  1175. return null;
  1176. };
  1177. /**
  1178. * Finds an element using by evaluating the specfied string.
  1179. */
  1180. BrowserBot.prototype.locateElementByDomTraversal = function(domTraversal, document, window) {
  1181. var browserbot = this.browserbot;
  1182. var element = null;
  1183. try {
  1184. element = eval(domTraversal);
  1185. } catch (e) {
  1186. return null;
  1187. }
  1188. if (!element) {
  1189. return null;
  1190. }
  1191. return element;
  1192. };
  1193. BrowserBot.prototype.locateElementByDomTraversal.prefix = "dom";
  1194. /**
  1195. * Finds an element identified by the xpath expression. Expressions _must_
  1196. * begin with "//".
  1197. */
  1198. BrowserBot.prototype.locateElementByXPath = function(xpath, inDocument, inWindow) {
  1199. var results = eval_xpath(xpath, inDocument, {
  1200. returnOnFirstMatch : true,
  1201. ignoreAttributesWithoutValue: this.ignoreAttributesWithoutValue,
  1202. allowNativeXpath : this.allow