PageRenderTime 64ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/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
Possible License(s): Apache-2.0
  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.allowNativeXpath,
  1203. xpathLibrary : this.xpathLibrary,
  1204. namespaceResolver : this._namespaceResolver
  1205. });
  1206. return (results.length > 0) ? results[0] : null;
  1207. };
  1208. BrowserBot.prototype._namespaceResolver = function(prefix) {
  1209. if (prefix == 'html' || prefix == 'xhtml' || prefix == 'x') {
  1210. return 'http://www.w3.org/1999/xhtml';
  1211. } else if (prefix == 'mathml') {
  1212. return 'http://www.w3.org/1998/Math/MathML';
  1213. } else {
  1214. throw new Error("Unknown namespace: " + prefix + ".");
  1215. }
  1216. }
  1217. /**
  1218. * Returns the number of xpath results.
  1219. */
  1220. BrowserBot.prototype.evaluateXPathCount = function(xpath, inDocument) {
  1221. var results = eval_xpath(xpath, inDocument, {
  1222. ignoreAttributesWithoutValue: this.ignoreAttributesWithoutValue,
  1223. allowNativeXpath : this.allowNativeXpath,
  1224. xpathLibrary : this.xpathLibrary,
  1225. namespaceResolver : this._namespaceResolver
  1226. });
  1227. return results.length;
  1228. };
  1229. /**
  1230. * Finds a link element with text matching the expression supplied. Expressions must
  1231. * begin with "link:".
  1232. */
  1233. BrowserBot.prototype.locateElementByLinkText = function(linkText, inDocument, inWindow) {
  1234. var links = inDocument.getElementsByTagName('a');
  1235. for (var i = 0; i < links.length; i++) {
  1236. var element = links[i];
  1237. if (PatternMatcher.matches(linkText, getText(element))) {
  1238. return element;
  1239. }
  1240. }
  1241. return null;
  1242. };
  1243. BrowserBot.prototype.locateElementByLinkText.prefix = "link";
  1244. /**
  1245. * Returns an attribute based on an attribute locator. This is made up of an element locator
  1246. * suffixed with @attribute-name.
  1247. */
  1248. BrowserBot.prototype.findAttribute = function(locator) {
  1249. // Split into locator + attributeName
  1250. var attributePos = locator.lastIndexOf("@");
  1251. var elementLocator = locator.slice(0, attributePos);
  1252. var attributeName = locator.slice(attributePos + 1);
  1253. // Find the element.
  1254. var element = this.findElement(elementLocator);
  1255. // Handle missing "class" attribute in IE.
  1256. if (browserVersion.isIE && attributeName == "class") {
  1257. attributeName = "className";
  1258. }
  1259. // Get the attribute value.
  1260. var attributeValue = element.getAttribute(attributeName);
  1261. // IE returns an object for the "style" attribute
  1262. if (attributeName == 'style' && typeof(attributeValue) != 'string') {
  1263. attributeValue = attributeValue.cssText;
  1264. }
  1265. return attributeValue ? attributeValue.toString() : null;
  1266. };
  1267. /*
  1268. * Select the specified option and trigger the relevant events of the element.
  1269. */
  1270. BrowserBot.prototype.selectOption = function(element, optionToSelect) {
  1271. triggerEvent(element, 'focus', false);
  1272. var changed = false;
  1273. for (var i = 0; i < element.options.length; i++) {
  1274. var option = element.options[i];
  1275. if (option.selected && option != optionToSelect) {
  1276. option.selected = false;
  1277. changed = true;
  1278. }
  1279. else if (!option.selected && option == optionToSelect) {
  1280. option.selected = true;
  1281. changed = true;
  1282. }
  1283. }
  1284. if (changed) {
  1285. triggerEvent(element, 'change', true);
  1286. }
  1287. };
  1288. /*
  1289. * Select the specified option and trigger the relevant events of the element.
  1290. */
  1291. BrowserBot.prototype.addSelection = function(element, option) {
  1292. this.checkMultiselect(element);
  1293. triggerEvent(element, 'focus', false);
  1294. if (!option.selected) {
  1295. option.selected = true;
  1296. triggerEvent(element, 'change', true);
  1297. }
  1298. };
  1299. /*
  1300. * Select the specified option and trigger the relevant events of the element.
  1301. */
  1302. BrowserBot.prototype.removeSelection = function(element, option) {
  1303. this.checkMultiselect(element);
  1304. triggerEvent(element, 'focus', false);
  1305. if (option.selected) {
  1306. option.selected = false;
  1307. triggerEvent(element, 'change', true);
  1308. }
  1309. };
  1310. BrowserBot.prototype.checkMultiselect = function(element) {
  1311. if (!element.multiple)
  1312. {
  1313. throw new SeleniumError("Not a multi-select");
  1314. }
  1315. };
  1316. BrowserBot.prototype.replaceText = function(element, stringValue) {
  1317. triggerEvent(element, 'focus', false);
  1318. triggerEvent(element, 'select', true);
  1319. var maxLengthAttr = element.getAttribute("maxLength");
  1320. var actualValue = stringValue;
  1321. if (maxLengthAttr != null) {
  1322. var maxLength = parseInt(maxLengthAttr);
  1323. if (stringValue.length > maxLength) {
  1324. actualValue = stringValue.substr(0, maxLength);
  1325. }
  1326. }
  1327. if (getTagName(element) == "body") {
  1328. if (element.ownerDocument && element.ownerDocument.designMode) {
  1329. var designMode = new String(element.ownerDocument.designMode).toLowerCase();
  1330. if (designMode = "on") {
  1331. // this must be a rich text control!
  1332. element.innerHTML = actualValue;
  1333. }
  1334. }
  1335. } else {
  1336. element.value = actualValue;
  1337. }
  1338. // DGF this used to be skipped in chrome URLs, but no longer. Is xpcnativewrappers to blame?
  1339. try {
  1340. triggerEvent(element, 'change', true);
  1341. } catch (e) {}
  1342. };
  1343. BrowserBot.prototype.submit = function(formElement) {
  1344. var actuallySubmit = true;
  1345. this._modifyElementTarget(formElement);
  1346. if (formElement.onsubmit) {
  1347. if (browserVersion.isHTA) {
  1348. // run the code in the correct window so alerts are handled correctly even in HTA mode
  1349. var win = this.browserbot.getCurrentWindow();
  1350. var now = new Date().getTime();
  1351. var marker = 'marker' + now;
  1352. win[marker] = formElement;
  1353. win.setTimeout("var actuallySubmit = "+marker+".onsubmit();" +
  1354. "if (actuallySubmit) { " +
  1355. marker+".submit(); " +
  1356. "if ("+marker+".target && !/^_/.test("+marker+".target)) {"+
  1357. "window.open('', "+marker+".target);"+
  1358. "}"+
  1359. "};"+
  1360. marker+"=null", 0);
  1361. // pause for up to 2s while this command runs
  1362. var terminationCondition = function () {
  1363. return !win[marker];
  1364. }
  1365. return Selenium.decorateFunctionWithTimeout(terminationCondition, 2000);
  1366. } else {
  1367. actuallySubmit = formElement.onsubmit();
  1368. if (actuallySubmit) {
  1369. formElement.submit();
  1370. if (formElement.target && !/^_/.test(formElement.target)) {
  1371. this.browserbot.openWindow('', formElement.target);
  1372. }
  1373. }
  1374. }
  1375. } else {
  1376. formElement.submit();
  1377. }
  1378. }
  1379. BrowserBot.prototype.clickElement = function(element, clientX, clientY) {
  1380. this._fireEventOnElement("click", element, clientX, clientY);
  1381. };
  1382. BrowserBot.prototype.doubleClickElement = function(element, clientX, clientY) {
  1383. this._fireEventOnElement("dblclick", element, clientX, clientY);
  1384. };
  1385. // The contextmenu event is fired when the user right-clicks to open the context menu
  1386. BrowserBot.prototype.contextMenuOnElement = function(element, clientX, clientY) {
  1387. this._fireEventOnElement("contextmenu", element, clientX, clientY);
  1388. };
  1389. BrowserBot.prototype._modifyElementTarget = function(element) {
  1390. if (element.target) {
  1391. if (element.target == "_blank" || /^selenium_blank/.test(element.target) ) {
  1392. var tagName = getTagName(element);
  1393. if (tagName == "a" || tagName == "form") {
  1394. var newTarget = "selenium_blank" + Math.round(100000 * Math.random());
  1395. LOG.warn("Link has target '_blank', which is not supported in Selenium! Randomizing target to be: " + newTarget);
  1396. this.browserbot.openWindow('', newTarget);
  1397. element.target = newTarget;
  1398. }
  1399. }
  1400. }
  1401. }
  1402. BrowserBot.prototype._handleClickingImagesInsideLinks = function(targetWindow, element) {
  1403. var itrElement = element;
  1404. while (itrElement != null) {
  1405. if (itrElement.href) {
  1406. targetWindow.location.href = itrElement.href;
  1407. break;
  1408. }
  1409. itrElement = itrElement.parentNode;
  1410. }
  1411. }
  1412. BrowserBot.prototype._getTargetWindow = function(element) {
  1413. var targetWindow = element.ownerDocument.defaultView;
  1414. if (element.target) {
  1415. targetWindow = this._getFrameFromGlobal(element.target);
  1416. }
  1417. return targetWindow;
  1418. }
  1419. BrowserBot.prototype._getFrameFromGlobal = function(target) {
  1420. if (target == "_self") {
  1421. return this.getCurrentWindow();
  1422. }
  1423. if (target == "_top") {
  1424. return this.topFrame;
  1425. } else if (target == "_parent") {
  1426. return this.getCurrentWindow().parent;
  1427. } else if (target == "_blank") {
  1428. // TODO should this set cleverer window defaults?
  1429. return this.getCurrentWindow().open('', '_blank');
  1430. }
  1431. var frameElement = this.findElementBy("implicit", target, this.topFrame.document, this.topFrame);
  1432. if (frameElement) {
  1433. return frameElement.contentWindow;
  1434. }
  1435. var win = this.getWindowByName(target);
  1436. if (win) return win;
  1437. return this.getCurrentWindow().open('', target);
  1438. }
  1439. BrowserBot.prototype.bodyText = function() {
  1440. if (!this.getDocument().body) {
  1441. throw new SeleniumError("Couldn't access document.body. Is this HTML page fully loaded?");
  1442. }
  1443. return getText(this.getDocument().body);
  1444. };
  1445. BrowserBot.prototype.getAllButtons = function() {
  1446. var elements = this.getDocument().getElementsByTagName('input');
  1447. var result = [];
  1448. for (var i = 0; i < elements.length; i++) {
  1449. if (elements[i].type == 'button' || elements[i].type == 'submit' || elements[i].type == 'reset') {
  1450. result.push(elements[i].id);
  1451. }
  1452. }
  1453. return result;
  1454. };
  1455. BrowserBot.prototype.getAllFields = function() {
  1456. var elements = this.getDocument().getElementsByTagName('input');
  1457. var result = [];
  1458. for (var i = 0; i < elements.length; i++) {
  1459. if (elements[i].type == 'text') {
  1460. result.push(elements[i].id);
  1461. }
  1462. }
  1463. return result;
  1464. };
  1465. BrowserBot.prototype.getAllLinks = function() {
  1466. var elements = this.getDocument().getElementsByTagName('a');
  1467. var result = [];
  1468. for (var i = 0; i < elements.length; i++) {
  1469. result.push(elements[i].id);
  1470. }
  1471. return result;
  1472. };
  1473. function isDefined(value) {
  1474. return typeof(value) != undefined;
  1475. }
  1476. BrowserBot.prototype.goBack = function() {
  1477. this.getCurrentWindow().history.back();
  1478. };
  1479. BrowserBot.prototype.goForward = function() {
  1480. this.getCurrentWindow().history.forward();
  1481. };
  1482. BrowserBot.prototype.close = function() {
  1483. if (browserVersion.isIE) {
  1484. // fix "do you want to close this window" warning in IE
  1485. // You can only close windows that you have opened.
  1486. // So, let's "open" it.
  1487. try {
  1488. this.topFrame.name=new Date().getTime();
  1489. window.open("", this.topFrame.name, "");
  1490. this.topFrame.close();
  1491. return;
  1492. } catch (e) {}
  1493. }
  1494. if (browserVersion.isChrome || browserVersion.isSafari || browserVersion.isOpera) {
  1495. this.topFrame.close();
  1496. } else {
  1497. this.getCurrentWindow().eval("window.top.close();");
  1498. }
  1499. };
  1500. BrowserBot.prototype.refresh = function() {
  1501. this.getCurrentWindow().location.reload(true);
  1502. };
  1503. /**
  1504. * Refine a list of elements using a filter.
  1505. */
  1506. BrowserBot.prototype.selectElementsBy = function(filterType, filter, elements) {
  1507. var filterFunction = BrowserBot.filterFunctions[filterType];
  1508. if (! filterFunction) {
  1509. throw new SeleniumError("Unrecognised element-filter type: '" + filterType + "'");
  1510. }
  1511. return filterFunction(filter, elements);
  1512. };
  1513. BrowserBot.filterFunctions = {};
  1514. BrowserBot.filterFunctions.name = function(name, elements) {
  1515. var selectedElements = [];
  1516. for (var i = 0; i < elements.length; i++) {
  1517. if (elements[i].name === name) {
  1518. selectedElements.push(elements[i]);
  1519. }
  1520. }
  1521. return selectedElements;
  1522. };
  1523. BrowserBot.filterFunctions.value = function(value, elements) {
  1524. var selectedElements = [];
  1525. for (var i = 0; i < elements.length; i++) {
  1526. if (elements[i].value === value) {
  1527. selectedElements.push(elements[i]);
  1528. }
  1529. }
  1530. return selectedElements;
  1531. };
  1532. BrowserBot.filterFunctions.index = function(index, elements) {
  1533. index = Number(index);
  1534. if (isNaN(index) || index < 0) {
  1535. throw new SeleniumError("Illegal Index: " + index);
  1536. }
  1537. if (elements.length <= index) {
  1538. throw new SeleniumError("Index out of range: " + index);
  1539. }
  1540. return [elements[index]];
  1541. };
  1542. BrowserBot.prototype.selectElements = function(filterExpr, elements, defaultFilterType) {
  1543. var filterType = (defaultFilterType || 'value');
  1544. // If there is a filter prefix, use the specified strategy
  1545. var result = filterExpr.match(/^([A-Za-z]+)=(.+)/);
  1546. if (result) {
  1547. filterType = result[1].toLowerCase();
  1548. filterExpr = result[2];
  1549. }
  1550. return this.selectElementsBy(filterType, filterExpr, elements);
  1551. };
  1552. /**
  1553. * Find an element by class
  1554. */
  1555. BrowserBot.prototype.locateElementByClass = function(locator, document) {
  1556. return elementFindFirstMatchingChild(document,
  1557. function(element) {
  1558. return element.className == locator
  1559. }
  1560. );
  1561. }
  1562. /**
  1563. * Find an element by alt
  1564. */
  1565. BrowserBot.prototype.locateElementByAlt = function(locator, document) {
  1566. return elementFindFirstMatchingChild(document,
  1567. function(element) {
  1568. return element.alt == locator
  1569. }
  1570. );
  1571. }
  1572. /**
  1573. * Find an element by css selector
  1574. */
  1575. BrowserBot.prototype.locateElementByCss = function(locator, document) {
  1576. var elements = eval_css(locator, document);
  1577. if (elements.length != 0)
  1578. return elements[0];
  1579. return null;
  1580. }
  1581. /**
  1582. * This function is responsible for mapping a UI specifier string to an element
  1583. * on the page, and returning it. If no element is found, null is returned.
  1584. * Returning null on failure to locate the element is part of the undocumented
  1585. * API for locator strategies.
  1586. */
  1587. BrowserBot.prototype.locateElementByUIElement = function(locator, inDocument) {
  1588. // offset locators are delimited by "->", which is much simpler than the
  1589. // previous scheme involving detecting the close-paren.
  1590. var locators = locator.split(/->/, 2);
  1591. var locatedElement = null;
  1592. var pageElements = UIMap.getInstance()
  1593. .getPageElements(locators[0], inDocument);
  1594. if (locators.length > 1) {
  1595. for (var i = 0; i < pageElements.length; ++i) {
  1596. var locatedElements = eval_locator(locators[1], inDocument,
  1597. pageElements[i]);
  1598. if (locatedElements.length) {
  1599. locatedElement = locatedElements[0];
  1600. break;
  1601. }
  1602. }
  1603. }
  1604. else if (pageElements.length) {
  1605. locatedElement = pageElements[0];
  1606. }
  1607. return locatedElement;
  1608. }
  1609. BrowserBot.prototype.locateElementByUIElement.prefix = 'ui';
  1610. // define a function used to compare the result of a close UI element
  1611. // match with the actual interacted element. If they are close enough
  1612. // according to the heuristic, consider them a match.
  1613. /**
  1614. * A heuristic function for comparing a node with a target node. Typically the
  1615. * node is specified in a UI element definition, while the target node is
  1616. * returned by the recorder as the leaf element which had some event enacted
  1617. * upon it. This particular heuristic covers the case where the anchor element
  1618. * contains other inline tags, such as "em" or "img".
  1619. *
  1620. * @param node the node being compared to the target node
  1621. * @param target the target node
  1622. * @return true if node equals target, or if node is a link
  1623. * element and target is its descendant, or if node has
  1624. * an onclick attribute and target is its descendant.
  1625. * False otherwise.
  1626. */
  1627. BrowserBot.prototype.locateElementByUIElement.is_fuzzy_match = function(node, target) {
  1628. try {
  1629. var isMatch = (
  1630. (node == target) ||
  1631. ((node.nodeName == 'A' || node.onclick) && is_ancestor(node, target))
  1632. );
  1633. return isMatch;
  1634. }
  1635. catch (e) {
  1636. return false;
  1637. }
  1638. };
  1639. /*****************************************************************/
  1640. /* BROWSER-SPECIFIC FUNCTIONS ONLY AFTER THIS LINE */
  1641. function MozillaBrowserBot(frame) {
  1642. BrowserBot.call(this, frame);
  1643. }
  1644. objectExtend(MozillaBrowserBot.prototype, BrowserBot.prototype);
  1645. function KonquerorBrowserBot(frame) {
  1646. BrowserBot.call(this, frame);
  1647. }
  1648. objectExtend(KonquerorBrowserBot.prototype, BrowserBot.prototype);
  1649. KonquerorBrowserBot.prototype.setIFrameLocation = function(iframe, location) {
  1650. // Window doesn't fire onload event when setting src to the current value,
  1651. // so we set it to blank first.
  1652. iframe.src = "about:blank";
  1653. iframe.src = location;
  1654. };
  1655. KonquerorBrowserBot.prototype.setOpenLocation = function(win, loc) {
  1656. // Window doesn't fire onload event when setting src to the current value,
  1657. // so we just refresh in that case instead.
  1658. loc = absolutify(loc, this.baseUrl);
  1659. loc = canonicalize(loc);
  1660. var startUrl = win.location.href;
  1661. if ("about:blank" != win.location.href) {
  1662. var startLoc = parseUrl(win.location.href);
  1663. startLoc.hash = null;
  1664. var startUrl = reassembleLocation(startLoc);
  1665. }
  1666. LOG.debug("startUrl="+startUrl);
  1667. LOG.debug("win.location.href="+win.location.href);
  1668. LOG.debug("loc="+loc);
  1669. if (startUrl == loc) {
  1670. LOG.debug("opening exact same location");
  1671. this.refresh();
  1672. } else {
  1673. LOG.debug("locations differ");
  1674. win.location.href = loc;
  1675. }
  1676. // force the current polling thread to detect a page load
  1677. var marker = this.isPollingForLoad(win);
  1678. if (marker) {
  1679. delete win.location[marker];
  1680. }
  1681. };
  1682. KonquerorBrowserBot.prototype._isSameDocument = function(originalDocument, currentDocument) {
  1683. // under Konqueror, there may be this case:
  1684. // originalDocument and currentDocument are different objects
  1685. // while their location are same.
  1686. if (originalDocument) {
  1687. return originalDocument.location == currentDocument.location
  1688. } else {
  1689. return originalDocument === currentDocument;
  1690. }
  1691. };
  1692. function SafariBrowserBot(frame) {
  1693. BrowserBot.call(this, frame);
  1694. }
  1695. objectExtend(SafariBrowserBot.prototype, BrowserBot.prototype);
  1696. SafariBrowserBot.prototype.setIFrameLocation = KonquerorBrowserBot.prototype.setIFrameLocation;
  1697. SafariBrowserBot.prototype.setOpenLocation = KonquerorBrowserBot.prototype.setOpenLocation;
  1698. function OperaBrowserBot(frame) {
  1699. BrowserBot.call(this, frame);
  1700. }
  1701. objectExtend(OperaBrowserBot.prototype, BrowserBot.prototype);
  1702. OperaBrowserBot.prototype.setIFrameLocation = function(iframe, location) {
  1703. if (iframe.src == location) {
  1704. iframe.src = location + '?reload';
  1705. } else {
  1706. iframe.src = location;
  1707. }
  1708. }
  1709. function IEBrowserBot(frame) {
  1710. BrowserBot.call(this, frame);
  1711. }
  1712. objectExtend(IEBrowserBot.prototype, BrowserBot.prototype);
  1713. IEBrowserBot.prototype._handleClosedSubFrame = function(testWindow, doNotModify) {
  1714. if (this.proxyInjectionMode) {
  1715. return testWindow;
  1716. }
  1717. try {
  1718. testWindow.location.href;
  1719. this.permDenied = 0;
  1720. } catch (e) {
  1721. this.permDenied++;
  1722. }
  1723. if (this._windowClosed(testWindow) || this.permDenied > 4) {
  1724. if (this.isSubFrameSelected) {
  1725. LOG.warn("Current subframe appears to have closed; selecting top frame");
  1726. this.selectFrame("relative=top");
  1727. return this.getCurrentWindow(doNotModify);
  1728. } else {
  1729. var closedError = new SeleniumError("Current window or frame is closed!");
  1730. closedError.windowClosed = true;
  1731. throw closedError;
  1732. }
  1733. }
  1734. return testWindow;
  1735. };
  1736. IEBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
  1737. BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);
  1738. // we will call the previous version of this method from within our own interception
  1739. oldShowModalDialog = windowToModify.showModalDialog;
  1740. windowToModify.showModalDialog = function(url, args, features) {
  1741. // Get relative directory to where TestRunner.html lives
  1742. // A risky assumption is that the user's TestRunner is named TestRunner.html
  1743. var doc_location = document.location.toString();
  1744. var end_of_base_ref = doc_location.indexOf('TestRunner.html');
  1745. var base_ref = doc_location.substring(0, end_of_base_ref);
  1746. var runInterval = '';
  1747. // Only set run interval if options is defined
  1748. if (typeof(window.runOptions) != 'undefined') {
  1749. runInterval = "&runInterval=" + runOptions.runInterval;
  1750. }
  1751. var testRunnerURL = "TestRunner.html?auto=true&singletest="
  1752. + escape(browserBot.modalDialogTest)
  1753. + "&autoURL="
  1754. + escape(url)
  1755. + runInterval;
  1756. var fullURL = base_ref + testRunnerURL;
  1757. browserBot.modalDialogTest = null;
  1758. // If using proxy injection mode
  1759. if (this.proxyInjectionMode) {
  1760. var sessionId = runOptions.getSessionId();
  1761. if (sessionId == undefined) {
  1762. sessionId = injectedSessionId;
  1763. }
  1764. if (sessionId != undefined) {
  1765. LOG.debug("Invoking showModalDialog and injecting URL " + fullURL);
  1766. }
  1767. fullURL = url;
  1768. }
  1769. var returnValue = oldShowModalDialog(fullURL, args, features);
  1770. return returnValue;
  1771. };
  1772. };
  1773. IEBrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads = function(windowObject) {
  1774. this.pageUnloading = false;
  1775. var self = this;
  1776. var pageUnloadDetector = function() {
  1777. self.pageUnloading = true;
  1778. };
  1779. windowObject.attachEvent("onbeforeunload", pageUnloadDetector);
  1780. BrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads.call(this, windowObject);
  1781. };
  1782. IEBrowserBot.prototype.pollForLoad = function(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker) {
  1783. LOG.debug("IEBrowserBot.pollForLoad: " + marker);
  1784. if (!this.permDeniedCount[marker]) this.permDeniedCount[marker] = 0;
  1785. BrowserBot.prototype.pollForLoad.call(this, loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
  1786. if (this.pageLoadError) {
  1787. if (this.pageUnloading) {
  1788. var self = this;
  1789. LOG.debug("pollForLoad UNLOADING (" + marker + "): caught exception while firing events on unloading page: " + this.pageLoadError.message);
  1790. this.reschedulePoller(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
  1791. this.pageLoadError = null;
  1792. return;
  1793. } else if (((this.pageLoadError.message == "Permission denied") || (/^Access is denied/.test(this.pageLoadError.message)))
  1794. && this.permDeniedCount[marker]++ < 8) {
  1795. if (this.permDeniedCount[marker] > 4) {
  1796. var canAccessThisWindow;
  1797. var canAccessCurrentlySelectedWindow;
  1798. try {
  1799. windowObject.location.href;
  1800. canAccessThisWindow = true;
  1801. } catch (e) {}
  1802. try {
  1803. this.getCurrentWindow(true).location.href;
  1804. canAccessCurrentlySelectedWindow = true;
  1805. } catch (e) {}
  1806. if (canAccessCurrentlySelectedWindow & !canAccessThisWindow) {
  1807. LOG.debug("pollForLoad (" + marker + ") ABORTING: " + this.pageLoadError.message + " (" + this.permDeniedCount[marker] + "), but the currently selected window is fine");
  1808. // returning without rescheduling
  1809. this.pageLoadError = null;
  1810. return;
  1811. }
  1812. }
  1813. var self = this;
  1814. LOG.debug("pollForLoad (" + marker + "): " + this.pageLoadError.message + " (" + this.permDeniedCount[marker] + "), waiting to see if it goes away");
  1815. this.reschedulePoller(loadFunction, windowObject, originalDocument, originalLocation, originalHref, marker);
  1816. this.pageLoadError = null;
  1817. return;
  1818. }
  1819. //handy for debugging!
  1820. //throw this.pageLoadError;
  1821. }
  1822. };
  1823. IEBrowserBot.prototype._windowClosed = function(win) {
  1824. try {
  1825. var c = win.closed;
  1826. // frame windows claim to be non-closed when their parents are closed
  1827. // but you can't access their document objects in that case
  1828. if (!c) {
  1829. try {
  1830. win.document;
  1831. } catch (de) {
  1832. if (de.message == "Permission denied") {
  1833. // the window is probably unloading, which means it's probably not closed yet
  1834. return false;
  1835. }
  1836. else if (/^Access is denied/.test(de.message)) {
  1837. // rare variation on "Permission denied"?
  1838. LOG.debug("IEBrowserBot.windowClosed: got " + de.message + " (this.pageUnloading=" + this.pageUnloading + "); assuming window is unloading, probably not closed yet");
  1839. return false;
  1840. } else {
  1841. // this is probably one of those frame window situations
  1842. LOG.debug("IEBrowserBot.windowClosed: couldn't read win.document, assume closed: " + de.message + " (this.pageUnloading=" + this.pageUnloading + ")");
  1843. return true;
  1844. }
  1845. }
  1846. }
  1847. if (c == null) {
  1848. LOG.debug("IEBrowserBot.windowClosed: win.closed was null, assuming closed");
  1849. return true;
  1850. }
  1851. return c;
  1852. } catch (e) {
  1853. LOG.debug("IEBrowserBot._windowClosed: Got an exception trying to read win.closed; we'll have to take a guess!");
  1854. if (browserVersion.isHTA) {
  1855. if (e.message == "Permission denied") {
  1856. // the window is probably unloading, which means it's not closed yet
  1857. return false;
  1858. } else {
  1859. // there's a good chance that we've lost contact with the window object if it is closed
  1860. return true;
  1861. }
  1862. } else {
  1863. // the window is probably unloading, which means it's not closed yet
  1864. return false;
  1865. }
  1866. }
  1867. };
  1868. /**
  1869. * In IE, getElementById() also searches by name - this is an optimisation for IE.
  1870. */
  1871. IEBrowserBot.prototype.locateElementByIdentifer = function(identifier, inDocument, inWindow) {
  1872. return inDocument.getElementById(identifier);
  1873. };
  1874. SafariBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
  1875. BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);
  1876. var originalOpen = windowToModify.open;
  1877. /*
  1878. * Safari seems to be broken, so that when we manually trigger the onclick method
  1879. * of a button/href, any window.open calls aren't resolved relative to the app location.
  1880. * So here we replace the open() method with one that does resolve the url correctly.
  1881. */
  1882. windowToModify.open = function(url, windowName, windowFeatures, replaceFlag) {
  1883. if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/")) {
  1884. return originalOpen(url, windowName, windowFeatures, replaceFlag);
  1885. }
  1886. // Reduce the current path to the directory
  1887. var currentPath = windowToModify.location.pathname || "/";
  1888. currentPath = currentPath.replace(/\/[^\/]*$/, "/");
  1889. // Remove any leading "./" from the new url.
  1890. url = url.replace(/^\.\//, "");
  1891. newUrl = currentPath + url;
  1892. var openedWindow = originalOpen(newUrl, windowName, windowFeatures, replaceFlag);
  1893. LOG.debug("window.open call intercepted; window ID (which you can use with selectWindow()) is \"" + windowName + "\"");
  1894. if (windowName!=null) {
  1895. openedWindow["seleniumWindowName"] = windowName;
  1896. }
  1897. return openedWindow;
  1898. };
  1899. };
  1900. MozillaBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
  1901. var win = this.getCurrentWindow();
  1902. triggerEvent(element, 'focus', false);
  1903. // Add an event listener that detects if the default action has been prevented.
  1904. // (This is caused by a javascript onclick handler returning false)
  1905. // we capture the whole event, rather than the getPreventDefault() state at the time,
  1906. // because we need to let the entire event bubbling and capturing to go through
  1907. // before making a decision on whether we should force the href
  1908. var savedEvent = null;
  1909. element.addEventListener(eventType, function(evt) {
  1910. savedEvent = evt;
  1911. }, false);
  1912. this._modifyElementTarget(element);
  1913. // Trigger the event.
  1914. this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
  1915. if (this._windowClosed(win)) {
  1916. return;
  1917. }
  1918. // Perform the link action if preventDefault was set.
  1919. // In chrome URL, the link action is already executed by triggerMouseEvent.
  1920. if (!browserVersion.isChrome && savedEvent != null && !savedEvent.getPreventDefault()) {
  1921. var targetWindow = this.browserbot._getTargetWindow(element);
  1922. if (element.href) {
  1923. targetWindow.location.href = element.href;
  1924. } else {
  1925. this.browserbot._handleClickingImagesInsideLinks(targetWindow, element);
  1926. }
  1927. }
  1928. };
  1929. OperaBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
  1930. var win = this.getCurrentWindow();
  1931. triggerEvent(element, 'focus', false);
  1932. this._modifyElementTarget(element);
  1933. // Trigger the click event.
  1934. this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
  1935. if (this._windowClosed(win)) {
  1936. return;
  1937. }
  1938. };
  1939. KonquerorBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
  1940. var win = this.getCurrentWindow();
  1941. triggerEvent(element, 'focus', false);
  1942. this._modifyElementTarget(element);
  1943. if (element[eventType]) {
  1944. element[eventType]();
  1945. }
  1946. else {
  1947. this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
  1948. }
  1949. if (this._windowClosed(win)) {
  1950. return;
  1951. }
  1952. };
  1953. SafariBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
  1954. triggerEvent(element, 'focus', false);
  1955. var wasChecked = element.checked;
  1956. this._modifyElementTarget(element);
  1957. // For form element it is simple.
  1958. if (element[eventType]) {
  1959. element[eventType]();
  1960. }
  1961. // For links and other elements, event emulation is required.
  1962. else {
  1963. var targetWindow = this.browserbot._getTargetWindow(element);
  1964. // todo: deal with anchors?
  1965. this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
  1966. }
  1967. };
  1968. SafariBrowserBot.prototype.refresh = function() {
  1969. var win = this.getCurrentWindow();
  1970. if (win.location.hash) {
  1971. // DGF Safari refuses to refresh when there's a hash symbol in the URL
  1972. win.location.hash = "";
  1973. var actuallyReload = function() {
  1974. win.location.reload(true);
  1975. }
  1976. window.setTimeout(actuallyReload, 1);
  1977. } else {
  1978. win.location.reload(true);
  1979. }
  1980. };
  1981. IEBrowserBot.prototype._fireEventOnElement = function(eventType, element, clientX, clientY) {
  1982. var win = this.getCurrentWindow();
  1983. triggerEvent(element, 'focus', false);
  1984. var wasChecked = element.checked;
  1985. // Set a flag that records if the page will unload - this isn't always accurate, because
  1986. // <a href="javascript:alert('foo'):"> triggers the onbeforeunload event, even thought the page won't unload
  1987. var pageUnloading = false;
  1988. var pageUnloadDetector = function() {
  1989. pageUnloading = true;
  1990. };
  1991. win.attachEvent("onbeforeunload", pageUnloadDetector);
  1992. this._modifyElementTarget(element);
  1993. if (element[eventType]) {
  1994. element[eventType]();
  1995. }
  1996. else {
  1997. this.browserbot.triggerMouseEvent(element, eventType, true, clientX, clientY);
  1998. }
  1999. // If the page is going to unload - still attempt to fire any subsequent events.
  2000. // However, we can't guarantee that the page won't unload half way through, so we need to handle exceptions.
  2001. try {
  2002. win.detachEvent("onbeforeunload", pageUnloadDetector);
  2003. if (this._windowClosed(win)) {
  2004. return;
  2005. }
  2006. // Onchange event is not triggered automatically in IE.
  2007. if (isDefined(element.checked) && wasChecked != element.checked) {
  2008. triggerEvent(element, 'change', true);
  2009. }
  2010. }
  2011. catch (e) {
  2012. // If the page is unloading, we may get a "Permission denied" or "Unspecified error".
  2013. // Just ignore it, because the document may have unloaded.
  2014. if (pageUnloading) {
  2015. LOG.logHook = function() {
  2016. };
  2017. LOG.warn("Caught exception when firing events on unloading page: " + e.message);
  2018. return;
  2019. }
  2020. throw e;
  2021. }
  2022. };