michael@0: /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this file, michael@0: * You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /** michael@0: * The ElementManager manages DOM references and interactions with elements. michael@0: * According to the WebDriver spec (http://code.google.com/p/selenium/wiki/JsonWireProtocol), the michael@0: * server sends the client an element reference, and maintains the map of reference to element. michael@0: * The client uses this reference when querying/interacting with the element, and the michael@0: * server uses maps this reference to the actual element when it executes the command. michael@0: */ michael@0: michael@0: this.EXPORTED_SYMBOLS = [ michael@0: "ElementManager", michael@0: "CLASS_NAME", michael@0: "SELECTOR", michael@0: "ID", michael@0: "NAME", michael@0: "LINK_TEXT", michael@0: "PARTIAL_LINK_TEXT", michael@0: "TAG", michael@0: "XPATH" michael@0: ]; michael@0: michael@0: const DOCUMENT_POSITION_DISCONNECTED = 1; michael@0: michael@0: let uuidGen = Components.classes["@mozilla.org/uuid-generator;1"] michael@0: .getService(Components.interfaces.nsIUUIDGenerator); michael@0: michael@0: this.CLASS_NAME = "class name"; michael@0: this.SELECTOR = "css selector"; michael@0: this.ID = "id"; michael@0: this.NAME = "name"; michael@0: this.LINK_TEXT = "link text"; michael@0: this.PARTIAL_LINK_TEXT = "partial link text"; michael@0: this.TAG = "tag name"; michael@0: this.XPATH = "xpath"; michael@0: michael@0: function ElementException(msg, num, stack) { michael@0: this.message = msg; michael@0: this.code = num; michael@0: this.stack = stack; michael@0: } michael@0: michael@0: this.ElementManager = function ElementManager(notSupported) { michael@0: this.seenItems = {}; michael@0: this.timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); michael@0: this.elementStrategies = [CLASS_NAME, SELECTOR, ID, NAME, LINK_TEXT, PARTIAL_LINK_TEXT, TAG, XPATH]; michael@0: for (let i = 0; i < notSupported.length; i++) { michael@0: this.elementStrategies.splice(this.elementStrategies.indexOf(notSupported[i]), 1); michael@0: } michael@0: } michael@0: michael@0: ElementManager.prototype = { michael@0: /** michael@0: * Reset values michael@0: */ michael@0: reset: function EM_clear() { michael@0: this.seenItems = {}; michael@0: }, michael@0: michael@0: /** michael@0: * Add element to list of seen elements michael@0: * michael@0: * @param nsIDOMElement element michael@0: * The element to add michael@0: * michael@0: * @return string michael@0: * Returns the server-assigned reference ID michael@0: */ michael@0: addToKnownElements: function EM_addToKnownElements(element) { michael@0: for (let i in this.seenItems) { michael@0: let foundEl = null; michael@0: try { michael@0: foundEl = this.seenItems[i].get(); michael@0: } michael@0: catch(e) {} michael@0: if (foundEl) { michael@0: if (XPCNativeWrapper(foundEl) == XPCNativeWrapper(element)) { michael@0: return i; michael@0: } michael@0: } michael@0: else { michael@0: //cleanup reference to GC'd element michael@0: delete this.seenItems[i]; michael@0: } michael@0: } michael@0: var id = uuidGen.generateUUID().toString(); michael@0: this.seenItems[id] = Components.utils.getWeakReference(element); michael@0: return id; michael@0: }, michael@0: michael@0: /** michael@0: * Retrieve element from its unique ID michael@0: * michael@0: * @param String id michael@0: * The DOM reference ID michael@0: * @param nsIDOMWindow win michael@0: * The window that contains the element michael@0: * michael@0: * @returns nsIDOMElement michael@0: * Returns the element or throws Exception if not found michael@0: */ michael@0: getKnownElement: function EM_getKnownElement(id, win) { michael@0: let el = this.seenItems[id]; michael@0: if (!el) { michael@0: throw new ElementException("Element has not been seen before. Id given was " + id, 17, null); michael@0: } michael@0: try { michael@0: el = el.get(); michael@0: } michael@0: catch(e) { michael@0: el = null; michael@0: delete this.seenItems[id]; michael@0: } michael@0: // use XPCNativeWrapper to compare elements; see bug 834266 michael@0: let wrappedWin = XPCNativeWrapper(win); michael@0: if (!el || michael@0: !(XPCNativeWrapper(el).ownerDocument == wrappedWin.document) || michael@0: (XPCNativeWrapper(el).compareDocumentPosition(wrappedWin.document.documentElement) & michael@0: DOCUMENT_POSITION_DISCONNECTED)) { michael@0: throw new ElementException("The element reference is stale. Either the element " + michael@0: "is no longer attached to the DOM or the page has been refreshed.", 10, null); michael@0: } michael@0: return el; michael@0: }, michael@0: michael@0: /** michael@0: * Convert values to primitives that can be transported over the michael@0: * Marionette protocol. michael@0: * michael@0: * This function implements the marshaling algorithm defined in the michael@0: * WebDriver specification: michael@0: * michael@0: * https://dvcs.w3.org/hg/webdriver/raw-file/tip/webdriver-spec.html#synchronous-javascript-execution michael@0: * michael@0: * @param object val michael@0: * object to be marshaled michael@0: * michael@0: * @return object michael@0: * Returns a JSON primitive or Object michael@0: */ michael@0: wrapValue: function EM_wrapValue(val) { michael@0: let result = null; michael@0: michael@0: switch (typeof(val)) { michael@0: case "undefined": michael@0: result = null; michael@0: break; michael@0: michael@0: case "string": michael@0: case "number": michael@0: case "boolean": michael@0: result = val; michael@0: break; michael@0: michael@0: case "object": michael@0: let type = Object.prototype.toString.call(val); michael@0: if (type == "[object Array]" || michael@0: type == "[object NodeList]") { michael@0: result = []; michael@0: for (let i = 0; i < val.length; ++i) { michael@0: result.push(this.wrapValue(val[i])); michael@0: } michael@0: } michael@0: else if (val == null) { michael@0: result = null; michael@0: } michael@0: else if (val.nodeType == 1) { michael@0: result = {'ELEMENT': this.addToKnownElements(val)}; michael@0: } michael@0: else { michael@0: result = {}; michael@0: for (let prop in val) { michael@0: result[prop] = this.wrapValue(val[prop]); michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: michael@0: return result; michael@0: }, michael@0: michael@0: /** michael@0: * Convert any ELEMENT references in 'args' to the actual elements michael@0: * michael@0: * @param object args michael@0: * Arguments passed in by client michael@0: * @param nsIDOMWindow win michael@0: * The window that contains the elements michael@0: * michael@0: * @returns object michael@0: * Returns the objects passed in by the client, with the michael@0: * reference IDs replaced by the actual elements. michael@0: */ michael@0: convertWrappedArguments: function EM_convertWrappedArguments(args, win) { michael@0: let converted; michael@0: switch (typeof(args)) { michael@0: case 'number': michael@0: case 'string': michael@0: case 'boolean': michael@0: converted = args; michael@0: break; michael@0: case 'object': michael@0: if (args == null) { michael@0: converted = null; michael@0: } michael@0: else if (Object.prototype.toString.call(args) == '[object Array]') { michael@0: converted = []; michael@0: for (let i in args) { michael@0: converted.push(this.convertWrappedArguments(args[i], win)); michael@0: } michael@0: } michael@0: else if (typeof(args['ELEMENT'] === 'string') && michael@0: args.hasOwnProperty('ELEMENT')) { michael@0: converted = this.getKnownElement(args['ELEMENT'], win); michael@0: if (converted == null) michael@0: throw new ElementException("Unknown element: " + args['ELEMENT'], 500, null); michael@0: } michael@0: else { michael@0: converted = {}; michael@0: for (let prop in args) { michael@0: converted[prop] = this.convertWrappedArguments(args[prop], win); michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: return converted; michael@0: }, michael@0: michael@0: /* michael@0: * Execute* helpers michael@0: */ michael@0: michael@0: /** michael@0: * Return an object with any namedArgs applied to it. Used michael@0: * to let clients use given names when refering to arguments michael@0: * in execute calls, instead of using the arguments list. michael@0: * michael@0: * @param object args michael@0: * list of arguments being passed in michael@0: * michael@0: * @return object michael@0: * If '__marionetteArgs' is in args, then michael@0: * it will return an object with these arguments michael@0: * as its members. michael@0: */ michael@0: applyNamedArgs: function EM_applyNamedArgs(args) { michael@0: namedArgs = {}; michael@0: args.forEach(function(arg) { michael@0: if (typeof(arg['__marionetteArgs']) === 'object') { michael@0: for (let prop in arg['__marionetteArgs']) { michael@0: namedArgs[prop] = arg['__marionetteArgs'][prop]; michael@0: } michael@0: } michael@0: }); michael@0: return namedArgs; michael@0: }, michael@0: michael@0: /** michael@0: * Find an element or elements starting at the document root or michael@0: * given node, using the given search strategy. Search michael@0: * will continue until the search timelimit has been reached. michael@0: * michael@0: * @param nsIDOMWindow win michael@0: * The window to search in michael@0: * @param object values michael@0: * The 'using' member of values will tell us which search michael@0: * method to use. The 'value' member tells us the value we michael@0: * are looking for. michael@0: * If this object has an 'element' member, this will be used michael@0: * as the start node instead of the document root michael@0: * If this object has a 'time' member, this number will be michael@0: * used to see if we have hit the search timelimit. michael@0: * @param function on_success michael@0: * The notification callback used when we are returning successfully. michael@0: * @param function on_error michael@0: The callback to invoke when an error occurs. michael@0: * @param boolean all michael@0: * If true, all found elements will be returned. michael@0: * If false, only the first element will be returned. michael@0: * michael@0: * @return nsIDOMElement or list of nsIDOMElements michael@0: * Returns the element(s) by calling the on_success function. michael@0: */ michael@0: find: function EM_find(win, values, searchTimeout, on_success, on_error, all, command_id) { michael@0: let startTime = values.time ? values.time : new Date().getTime(); michael@0: let startNode = (values.element != undefined) ? michael@0: this.getKnownElement(values.element, win) : win.document; michael@0: if (this.elementStrategies.indexOf(values.using) < 0) { michael@0: throw new ElementException("No such strategy.", 17, null); michael@0: } michael@0: let found = all ? this.findElements(values.using, values.value, win.document, startNode) : michael@0: this.findElement(values.using, values.value, win.document, startNode); michael@0: if (found) { michael@0: let type = Object.prototype.toString.call(found); michael@0: if ((type == '[object Array]') || (type == '[object HTMLCollection]') || (type == '[object NodeList]')) { michael@0: let ids = [] michael@0: for (let i = 0 ; i < found.length ; i++) { michael@0: ids.push(this.addToKnownElements(found[i])); michael@0: } michael@0: on_success(ids, command_id); michael@0: } michael@0: else { michael@0: let id = this.addToKnownElements(found); michael@0: on_success({'ELEMENT':id}, command_id); michael@0: } michael@0: return; michael@0: } else { michael@0: if (!searchTimeout || new Date().getTime() - startTime > searchTimeout) { michael@0: on_error("Unable to locate element: " + values.value, 7, null, command_id); michael@0: } else { michael@0: values.time = startTime; michael@0: this.timer.initWithCallback(this.find.bind(this, win, values, michael@0: searchTimeout, michael@0: on_success, on_error, all, michael@0: command_id), michael@0: 100, michael@0: Components.interfaces.nsITimer.TYPE_ONE_SHOT); michael@0: } michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Find a value by XPATH michael@0: * michael@0: * @param nsIDOMElement root michael@0: * Document root michael@0: * @param string value michael@0: * XPATH search string michael@0: * @param nsIDOMElement node michael@0: * start node michael@0: * michael@0: * @return nsIDOMElement michael@0: * returns the found element michael@0: */ michael@0: findByXPath: function EM_findByXPath(root, value, node) { michael@0: return root.evaluate(value, node, null, michael@0: Components.interfaces.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; michael@0: }, michael@0: michael@0: /** michael@0: * Find values by XPATH michael@0: * michael@0: * @param nsIDOMElement root michael@0: * Document root michael@0: * @param string value michael@0: * XPATH search string michael@0: * @param nsIDOMElement node michael@0: * start node michael@0: * michael@0: * @return object michael@0: * returns a list of found nsIDOMElements michael@0: */ michael@0: findByXPathAll: function EM_findByXPathAll(root, value, node) { michael@0: let values = root.evaluate(value, node, null, michael@0: Components.interfaces.nsIDOMXPathResult.ORDERED_NODE_ITERATOR_TYPE, null); michael@0: let elements = []; michael@0: let element = values.iterateNext(); michael@0: while (element) { michael@0: elements.push(element); michael@0: element = values.iterateNext(); michael@0: } michael@0: return elements; michael@0: }, michael@0: michael@0: /** michael@0: * Helper method to find. Finds one element using find's criteria michael@0: * michael@0: * @param string using michael@0: * String identifying which search method to use michael@0: * @param string value michael@0: * Value to look for michael@0: * @param nsIDOMElement rootNode michael@0: * Document root michael@0: * @param nsIDOMElement startNode michael@0: * Node from which we start searching michael@0: * michael@0: * @return nsIDOMElement michael@0: * Returns found element or throws Exception if not found michael@0: */ michael@0: findElement: function EM_findElement(using, value, rootNode, startNode) { michael@0: let element; michael@0: switch (using) { michael@0: case ID: michael@0: element = startNode.getElementById ? michael@0: startNode.getElementById(value) : michael@0: this.findByXPath(rootNode, './/*[@id="' + value + '"]', startNode); michael@0: break; michael@0: case NAME: michael@0: element = startNode.getElementsByName ? michael@0: startNode.getElementsByName(value)[0] : michael@0: this.findByXPath(rootNode, './/*[@name="' + value + '"]', startNode); michael@0: break; michael@0: case CLASS_NAME: michael@0: element = startNode.getElementsByClassName(value)[0]; //works for >=FF3 michael@0: break; michael@0: case TAG: michael@0: element = startNode.getElementsByTagName(value)[0]; //works for all elements michael@0: break; michael@0: case XPATH: michael@0: element = this.findByXPath(rootNode, value, startNode); michael@0: break; michael@0: case LINK_TEXT: michael@0: case PARTIAL_LINK_TEXT: michael@0: let allLinks = startNode.getElementsByTagName('A'); michael@0: for (let i = 0; i < allLinks.length && !element; i++) { michael@0: let text = allLinks[i].text; michael@0: if (PARTIAL_LINK_TEXT == using) { michael@0: if (text.indexOf(value) != -1) { michael@0: element = allLinks[i]; michael@0: } michael@0: } else if (text == value) { michael@0: element = allLinks[i]; michael@0: } michael@0: } michael@0: break; michael@0: case SELECTOR: michael@0: element = startNode.querySelector(value); michael@0: break; michael@0: default: michael@0: throw new ElementException("No such strategy", 500, null); michael@0: } michael@0: return element; michael@0: }, michael@0: michael@0: /** michael@0: * Helper method to find. Finds all element using find's criteria michael@0: * michael@0: * @param string using michael@0: * String identifying which search method to use michael@0: * @param string value michael@0: * Value to look for michael@0: * @param nsIDOMElement rootNode michael@0: * Document root michael@0: * @param nsIDOMElement startNode michael@0: * Node from which we start searching michael@0: * michael@0: * @return nsIDOMElement michael@0: * Returns found elements or throws Exception if not found michael@0: */ michael@0: findElements: function EM_findElements(using, value, rootNode, startNode) { michael@0: let elements = []; michael@0: switch (using) { michael@0: case ID: michael@0: value = './/*[@id="' + value + '"]'; michael@0: case XPATH: michael@0: elements = this.findByXPathAll(rootNode, value, startNode); michael@0: break; michael@0: case NAME: michael@0: elements = startNode.getElementsByName ? michael@0: startNode.getElementsByName(value) : michael@0: this.findByXPathAll(rootNode, './/*[@name="' + value + '"]', startNode); michael@0: break; michael@0: case CLASS_NAME: michael@0: elements = startNode.getElementsByClassName(value); michael@0: break; michael@0: case TAG: michael@0: elements = startNode.getElementsByTagName(value); michael@0: break; michael@0: case LINK_TEXT: michael@0: case PARTIAL_LINK_TEXT: michael@0: let allLinks = rootNode.getElementsByTagName('A'); michael@0: for (let i = 0; i < allLinks.length; i++) { michael@0: let text = allLinks[i].text; michael@0: if (PARTIAL_LINK_TEXT == using) { michael@0: if (text.indexOf(value) != -1) { michael@0: elements.push(allLinks[i]); michael@0: } michael@0: } else if (text == value) { michael@0: elements.push(allLinks[i]); michael@0: } michael@0: } michael@0: break; michael@0: case SELECTOR: michael@0: elements = Array.slice(startNode.querySelectorAll(value)); michael@0: break; michael@0: default: michael@0: throw new ElementException("No such strategy", 500, null); michael@0: } michael@0: return elements; michael@0: }, michael@0: }