How to use driver.setWindowPosition method in Appium

Best JavaScript code snippet using appium

wd.js

Source:wd.js Github

copy

Full Screen

1/*jshint node:true */2define([3	'dojo/node!wd',4	'dojo/node!wd/lib/webdriver',5	'dojo/node!wd/lib/element',6	'dojo/node!wd/lib/utils',7	'dojo/node!path',8	'dojo/promise/when',9	'dojo/Deferred',10	'dojo/topic',11	'./util'12], function (wd, WebDriver, Element, wdUtils, pathUtils, when, Deferred, topic, util) {13	if (!wd) {14		throw new Error('wd cannot be loaded in a browser environment');15	}16	// wd APIs are pretty awful17	if (Element.element) {18		Element = Element.element;19	}20	// Simplify moving mouse to an element21	if (!Element.prototype.moveTo) {22		Element.prototype.moveTo = function (offsetX, offsetY, cb) {23			this.browser.moveTo(this, offsetX, offsetY, cb);24		};25	}26	/**27	 * A hash map of names of methods that accept an element as the first argument.28	 */29	var elementArgumentMethods = {30		clickElement: true,31		submit: true,32		text: true,33		getTagName: true,34		clear: true,35		isSelected: true,36		getAttribute: true,37		getValue: true,38		isDisplayed: true,39		getLocation: true,40		getSize: true,41		getComputedCss: true,42		moveTo: true,43		flick: true,44		isVisible: true,45		isEnabled: true,46		// `type` must be used with element context or else this happens in Safari:47		// https://code.google.com/p/selenium/issues/detail?id=499648		type: true49	};50	/**51	 * A hash map of names of methods that operate using an element as the context. Only methods that do not have an52	 * entry in `elementArgumentMethods` of the same name are listed here, since they are just proxies back to those53	 * master methods.54	 */55	var elementContextMethods = {56		click: true,57		textPresent: true,58		equals: true59	};60	wdUtils.elementFuncTypes.forEach(function (type) {61		type = wdUtils.elFuncSuffix(type);62		[ 'element_',63			'element_OrNull',64			'element_IfExists',65			'waitForElement_',66			'waitForVisible_',67			'elements_'68		].forEach(function (wrapper) {69			var name = wrapper.replace('_', type);70			elementContextMethods[name] = true;71		});72	});73	/**74	 * A WebDriver instance with Promises/A interface methods instead of Node.js callback-style methods.75	 *76	 * @property {string} sessionId The session ID of the current remote session. Undefined until the session is77	 * successfully initialised using {@link init}.78	 *79	 * @property {function(desiredCapabilities:Object):PromisedWebDriver -> string} init80	 * Creates a new remote session with the desired capabilities. The first argument is a capabilities object.81	 * Resolves to the session ID of the new session. This method should never be called directly by testing code.82	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session83	 *84	 * @property {function():PromisedWebDriver -> Object} status85	 * Retrieves the status of the server. Resolves to an object with information on the server status.86	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/status87	 *88	 * @property {function():PromisedWebDriver -> Array.<Object>} sessions89	 * Retrieves a list of active sessions on the current server. Resolves to an array of objects containing the90	 * ID and map of capabilities for each session.91	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/sessions92	 *93	 * @property {function():PromisedWebDriver -> Object} sessionCapabilities94	 * Retrieves the list of capabilities defined for the current session. Resolves to a hash map of the capabilities95	 * of the current session.96	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId97	 *98	 * @property {function(url:string, name:string=):PromisedWebDriver} newWindow99	 * Opens a new window (using `window.open`) with the given URL and optionally a name for the new window.100	 * The window can later be accessed by name with the {@link window} method, or by getting the last handle101	 * returned by the {@link windowHandles} method.102	 *103	 * @property {function():PromisedWebDriver} close104	 * Closes the currently focused window.105	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId/window106	 *107	 * @property {function(name:string):PromisedWebDriver} window108	 * Changes focus to the window with the given name.109	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/window110	 *111	 * @property {function(id:(string|number|Element)):PromisedWebDriver} frame112	 * Changes focus to the frame (like `window.frames`) with the given name, index, or explicit element reference.113	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/frame114	 *115	 * @property {function():PromisedWebDriver -> string} windowName116	 * Retrieves the name of the currently focused window.117	 *118	 * @property {function():PromisedWebDriver -> string} windowHandle119	 * Retrieves the current window handle.120	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/window_handle121	 *122	 * @property {function():PromisedWebDriver -> Array.<string>} windowHandles123	 * Retrieves all window handles currently available within the session.124	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/window_handles125	 *126	 * @property {function():PromisedWebDriver} quit127	 * Destroys the current session. This method should never be called by testing code.128	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId129	 *130	 * @property {function(code:string):PromisedWebDriver -> *} eval131	 * Evaluates the given code using the `eval` function of the remote browser. Resolves to the value of the132	 * evaluated expression. It is recommended that `execute` be used instead of this function when possible.133	 *134	 * @property {function(code:string|Function):PromisedWebDriver -> *} execute135	 * Executes the given code or function within the remote browser. Resolves to the return value of the function.136	 * When a string is passed, it is invoked as with `new Function`. If a function is passed, it is serialised and137	 * passed to the remote browser, so when executed does not have access to anything from the original lexical scope.138	 * If the resolved value of an `execute` method is an Element, the element will be set as the current context for139	 * element-specific methods.140	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/execute141	 *142	 * @property {function(code:string|Function, args:Array=):PromisedWebDriver -> *} executeAsync143	 * Executes the given code or function within the remote browser, expecting that the code will invoke the callback144	 * that gets passed as the final argument to the function. For example:145	 *146	 * <pre>147	 * remote.executeAsync(function (timeout, callback) {148	 *     setTimeout(function () {149	 *         callback('returnValue');150	 *     }, timeout);151	 * }, [ 1000 ]);152	 * </pre>153	 *154	 * Note that `executeAsync` may not be supported by all Selenium drivers.155	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/execute_async156	 *157	 * @property {function(url:string):PromisedWebDriver} get158	 * Navigates the currently focused window to the given URL. Resolves when the browser `window.onload` event159	 * fires.160	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/url161	 *162	 * @property {function():PromisedWebDriver} refresh163	 * Refreshes the currently focused window.164	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/refresh165	 *166	 * @property {function(handle:string):PromisedWebDriver} maximize167	 * Maximises the window specified by `handle` if not already maximised. The special handle value "current" may be168	 * used to maximise the currently focused window.169	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/window/:windowHandle/maximize170	 *171	 * @property {function(handle:string=):PromisedWebDriver -> { width:number, height:number }} getWindowSize172	 * Gets the size of the window specified by `handle`. If no handle is specified, the size of the currently focused173	 * window is retrieved.174	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/window/:windowHandle/size175	 *176	 * @property {function(width:number, height:number, handle:string=):PromisedWebDriver} setWindowSize177	 * Sets the size of the window specified by `handle`. If no handle is specified, the size of the currently focused178	 * window is set.179	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/window/:windowHandle/size180	 *181	 * @property {function(handle:string=):PromisedWebDriver -> { x: number, y: number }} getWindowPosition182	 * Gets the position of the window specified by `handle`, relative to the top-left corner of the screen. If no183	 * handle is specified, the position of the currently focused window is retrieved.184	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/window/:windowHandle/position185	 *186	 * @property {function(x:number, y:number, handle:string=):PromisedWebDriver} setWindowPosition187	 * Sets the position of the window specified by `handle`, relative to the top-left corner of the screen. If no188	 * handle is specified, the position of the currently focused window is set.189	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/window/:windowHandle/position190	 *191	 * @property {function():PromisedWebDriver} forward192	 * Navigates forward in the browser history.193	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/forward194	 *195	 * @property {function():PromisedWebDriver} back196	 * Navigates backwards in the browser history.197	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/back198	 *199	 * @property {function(milliseconds:number):PromisedWebDriver} setImplicitWaitTimeout200	 * Sets the maximum amount of time the remote driver should poll for elements before giving up, in milliseconds.201	 * Defaults to 0ms (give up immediately).202	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/timeouts/implicit_wait203	 *204	 * @property {function(milliseconds:number):PromisedWebDriver} setAsyncScriptTimeout205	 * Sets the maximum amount of time the remote driver should wait for an asynchronous script to execute its callback206	 * before giving up, in milliseconds.207	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/timeouts/async_script208	 *209	 * @property {function(milliseconds:number):PromisedWebDriver} setPageLoadTimeout210	 * Sets the maximum amount of time the remote driver should wait for a page to finish loading before giving up,211	 * in milliseconds.212	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/timeouts213	 *214	 * @property {function():PromisedWebDriver -> string} takeScreenshot215	 * Takes a screenshot of the current page. Resolves to a base64-encoded PNG of the current page.216	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/screenshot217	 *218	 * @property {function(className:string):PromisedWebDriver -> Element} elementByClassName219	 * Retrieves the first element matching the given CSS class. If no such element exists, an error is raised.220	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element221	 *222	 * @property {function(className:string):PromisedWebDriver -> Element} elementByClassNameIfExists223	 * Retrieves the first element matching the given CSS class, or `undefined` if no such element exists.224	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element225	 *226	 * @property {function(className:string, timeout:number):PromisedWebDriver} waitForVisibleByClassName227	 * Waits until the first element matching the given CSS class becomes visible. If the element does not become228	 * visible before the timeout (in milliseconds), an error is raised.229	 *230	 * @property {function(className:string):PromisedWebDriver -> Array.<Element>} elementsByClassName231	 * Retrieves all elements matching the given CSS class.232	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements233	 *234	 * @property {function(selector:string):PromisedWebDriver -> Element} elementByCssSelector235	 * Retrieves the first element matching the given CSS selector. If no such element exists, an error is raised.236	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element237	 *238	 * @property {function(selector:string):PromisedWebDriver -> Element} elementByCssSelectorIfExists239	 * Retrieves the first element matching the given CSS selector, or `undefined` if no such element exists.240	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element241	 *242	 * @property {function(selector:string, timeout:number):PromisedWebDriver} waitForVisibleByCssSelector243	 * Waits until the first element matching the given CSS selector becomes visible. If the element does not become244	 * visible before the timeout (in milliseconds), an error is raised.245	 *246	 * @property {function(selector:string):PromisedWebDriver -> Array.<Element>} elementsByCssSelector247	 * Retrieves all elements matching the given CSS selector.248	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements249	 *250	 * @property {function(id:string):PromisedWebDriver -> Element} elementById251	 * Retrieves the first element matching the given ID. If no such element exists, an error is raised.252	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element253	 *254	 * @property {function(id:string):PromisedWebDriver -> Element} elementByIdIfExists255	 * Retrieves the first element matching the given ID, or `undefined` if no such element exists.256	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element257	 *258	 * @property {function(id:string, timeout:number):PromisedWebDriver} waitForVisibleById259	 * Waits until the first element matching the given ID becomes visible. If the element does not become260	 * visible before the timeout (in milliseconds), an error is raised.261	 *262	 * @property {function(id:string):PromisedWebDriver -> Array.<Element>} elementsById263	 * Retrieves all elements matching the given ID.264	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements265	 *266	 * @property {function(name:string):PromisedWebDriver -> Element} elementByName267	 * Retrieves the first element matching the given HTML name attribute. If no such element exists, an error is268	 * raised.269	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element270	 *271	 * @property {function(name:string):PromisedWebDriver -> Element} elementByNameIfExists272	 * Retrieves the first element matching the given HTML name attribute, or `undefined` if no such element exists.273	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element274	 *275	 * @property {function(name:string, timeout:number):PromisedWebDriver} waitForVisibleByName276	 * Waits until the first element matching the given HTML name attribute becomes visible. If the element does not277	 * become visible before the timeout (in milliseconds), an error is raised.278	 *279	 * @property {function(name:string):PromisedWebDriver -> Array.<Element>} elementsByName280	 * Retrieves all elements matching the given HTML name attribute.281	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements282	 *283	 * @property {function(linkText:string):PromisedWebDriver -> Element} elementByLinkText284	 * Retrieves the first link element (`<a>`) whose text contents exactly match the given text. If no such element285	 * exists, an error is raised.286	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element287	 *288	 * @property {function(linkText:string):PromisedWebDriver -> Element} elementByLinkTextIfExists289	 * Retrieves the first link element (`<a>`) whose text contents exactly match the given text, or `undefined` if no290	 * such element exists.291	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element292	 *293	 * @property {function(linkText:string, timeout:number):PromisedWebDriver} waitForVisibleByLinkText294	 * Waits until the first link element (`<a>`) whose text contents exactly match the given text becomes visible. If295	 * the element does not become visible before the timeout (in milliseconds), an error is raised.296	 *297	 * @property {function(linkText:string):PromisedWebDriver -> Array.<Element>} elementsByLinkText298	 * Retrieves all link elements (`<a>`) whose text contents exactly match the given text.299	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements300	 *301	 * @property {function(linkText:string):PromisedWebDriver -> Element} elementByPartialLinkText302	 * Retrieves the first link element (`<a>`) whose text contents contain the given text. If no such element303	 * exists, an error is raised.304	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element305	 *306	 * @property {function(linkText:string):PromisedWebDriver -> Element} elementByPartialLinkTextIfExists307	 * Retrieves the first link element (`<a>`) whose text contents contain the given text, or `undefined` if no308	 * such element exists.309	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element310	 *311	 * @property {function(linkText:string, timeout:number):PromisedWebDriver} waitForVisibleByPartialLinkText312	 * Waits until the first link element (`<a>`) whose text contents contain the given text becomes visible. If the313	 * element does not become visible before the timeout (in milliseconds), an error is raised.314	 *315	 * @property {function(linkText:string):PromisedWebDriver -> Array.<Element>} elementsByPartialLinkText316	 * Retrieves all link elements (`<a>`) whose text contents contain the given text.317	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements318	 *319	 * @property {function(tagName:string):PromisedWebDriver -> Element} elementByTagName320	 * Retrieves the first element with the given tag name. If no such element exists, an error is raised.321	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element322	 *323	 * @property {function(tagName:string):PromisedWebDriver -> Element} elementByTagNameIfExists324	 * Retrieves the first element with the given tag name, or `undefined` if no such element exists.325	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element326	 *327	 * @property {function(tagName:string, timeout:number):PromisedWebDriver} waitForVisibleByTagName328	 * Waits until the first element matching the given tag name becomes visible. If the element does not become329	 * visible before the timeout (in milliseconds), an error is raised.330	 *331	 * @property {function(tagName:string):PromisedWebDriver -> Array.<Element>} elementsByTagName332	 * Retrieves all elements with the given tag name.333	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements334	 *335	 * @property {function(selector:string):PromisedWebDriver -> Element} elementByXPath336	 * Retrieves the first element matching the given XPath selector. If no such element exists, an error is raised.337	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element338	 *339	 * @property {function(selector:string):PromisedWebDriver -> Element} elementByXPathIfExists340	 * Retrieves the first element matching the given XPath selector, or `undefined` if no such element exists.341	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element342	 *343	 * @property {function(selector:string, timeout:number):PromisedWebDriver} waitForVisibleByXPath344	 * Waits until the first element matching the given XPath selector becomes visible. If the element does not become345	 * visible before the timeout (in milliseconds), an error is raised.346	 *347	 * @property {function(selector:string):PromisedWebDriver -> Array.<Element>} elementsByXPath348	 * Retrieves all elements matching the given XPath selector.349	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/elements350	 *351	 * @property {function(element:Element=):PromisedWebDriver -> string} getTagName352	 * Retrieves the tag name of the given element. If no element is provided explicitly, the last stored context353	 * element will be used.354	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/name355	 *356	 * @property {function(element:Element=, name:string):PromisedWebDriver -> ?string} getAttribute357	 * Retrieves the value of the given attribute. If no element is provided explicitly, the last stored context358	 * element will be used.359	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/attribute/:name360	 *361	 * @property {function(element:Element=):PromisedWebDriver -> boolean} isDisplayed362	 * Determines if an element is currently being displayed. If no element is provided explicitly, the last stored363	 * context element will be used.364	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/displayed365	 *366	 * @property {function(element:Element=):PromisedWebDriver -> boolean} isEnabled367	 * Determines if an element is currently enabled. If no element is provided explicitly, the last stored context368	 * element will be used.369	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/enabled370	 *371	 * @property {function(element:Element=):PromisedWebDriver} clickElement372	 * Moves the pointer to an element and clicks on it. If no element is provided explicitly, the last stored context373	 * element will be used.374	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/:id/click375	 *376	 * @property {function(element:Element=, ):PromisedWebDriver} click377	 * Moves the pointer to an element and clicks on it. If no element is provided explicitly, the last stored context378	 * element will be used.379	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/:id/click380	 *381	 * @property {function(element:Element=, propertyName:string):PromisedWebDriver -> string} getComputedCss382	 * Retrieves the value of the CSS property given in `propertyName`. Note that `propertyName` should be specified383	 * using the CSS-style property name, not the JavaScript-style property name (e.g. `background-color` instead of384	 * `backgroundColor`). If no element is provided explicitly, the last stored context element will be used.385	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/css/:propertyName386	 *387	 * @property {function(element:Element=, otherElement:Element):PromisedWebDriver -> boolean} equalsElement388	 * Determines whether or not the two elements refer to the same DOM node. If no element is provided explicitly,389	 * the last stored context element will be used.390	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/equals/:other391	 *392	 * @property {function(element:Element=, otherElement:Element):PromisedWebDriver -> boolean} equals393	 * Determines whether or not the two elements refer to the same DOM node. If no element is provided explicitly,394	 * the last stored context element will be used.395	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/equals/:other396	 *397	 * @property {function(xspeed:number, yspeed:number):PromisedWebDriver} flick398	 * Performs a touch flick gesture at the given initial speed in pixels per second.399	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#session/:sessionId/touch/flick400	 *401	 * @property {function(element:Element=, xoffset:number, yoffset:number, speed:number):PromisedWebDriver} flick402	 * Performs a touch flick gesture starting at the given element and moving to the point at `xoffset,yoffset`403	 * relative to the centre of the given element at `speed` pixels per second. If no element is provided explicitly,404	 * the last stored context element will be used.405	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#session/:sessionId/touch/flick406	 *407	 * @property {function(element:Element=, xoffset:number=, yoffset:number=):PromisedWebDriver} moveTo408	 * Moves the pointer to the centre of the given element. If `xoffset` and `yoffset` are provided, move to that409	 * point relative to the top-left corner of the given element instead. If no element is provided explicitly,410	 * the last stored context element will be used.411	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/moveto412	 *413	 * @property {function(button:number=):PromisedWebDriver} buttonDown414	 * Press and hold a pointer button (i.e. mouse button). This method uses magic numbers for the button argument:415	 *416	 * * 0 corresponds to left button417	 * * 1 corresponds to middle button418	 * * 2 corresponds to right button419	 *420	 * If a button is not specified, it defaults to the left button.421	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/buttondown422	 *423	 * @property {function(button:number=):PromisedWebDriver} buttonUp424	 * Release a held pointer button (i.e. mouse button). This method uses magic numbers for the button argument:425	 *426	 * * 0 corresponds to left button427	 * * 1 corresponds to middle button428	 * * 2 corresponds to right button429	 *430	 * If a button is not specified, it defaults to the left button.431	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/buttonup432	 *433	 * @property {function():PromisedWebDriver} doubleclick434	 * Performs a double-click at the pointer's current position.435	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/doubleclick436	 *437	 * @property {function(element:Element=, keys:string):PromisedWebDriver} type438	 * Send a series of keystrokes to the given element. Non-text keys can be typed by using special Unicode PUA439	 * values; see the protocol documentation for more information. When using `type`, the entire operation is atomic,440	 * and any modifier keys set by the command string are implicitly released. If no element is provided explicitly,441	 * the last stored context element will be used.442	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/:id/value443	 *444	 * @property {function(keys:string):PromisedWebDriver} keys445	 * Send a series of keystrokes to the browser. Non-text keys can be typed by using special Unicode PUA values;446	 * see the protocol documentation for more information. When using `keys`, modifier keys set and not released447	 * will persist beyond the end of the command to enable testing of e.g. mouse actions while holding down modifier448	 * keys.449	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/keys450	 *451	 * @property {function(element:Element=):PromisedWebDriver} submit452	 * Submits the given form element. If no element is provided explicitly, the last stored context element will be453	 * used.454	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/:id/submit455	 *456	 * @property {function(element:Element=):PromisedWebDriver} clear457	 * Clears the content of a given `<textarea>` or `<input type="text">` element. If no element is provided458	 * explicitly, the last stored context element will be used.459	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/:id/clear460	 *461	 * @property {function():PromisedWebDriver -> string} title462	 * Retrieves the current title of the page.463	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/title464	 *465	 * @property {function():PromisedWebDriver -> string} source466	 * Retrieves the HTML source for the currently loaded page.467	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/source468	 *469	 * @property {function(element:Element=):PromisedWebDriver -> string} text470	 * Retrieves the currently visible text within the element. If no element is provided explicitly, the last stored471	 * context element will be used.472	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/text473	 *474	 * @property {function():PromisedWebDriver -> string} alertText475	 * Retrieves the text of the currently displayed JavaScript alert, confirm, or prompt dialog. If no dialog exists476	 * at the time this method is called, an error is raised.477	 * Note that `alertText` may not be supported by all Selenium drivers.478	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/alert_text479	 *480	 * @property {function(element:Element=, keys:string):PromisedWebDriver} alertKeys481	 * Send a series of keystrokes to an open prompt dialog. If no dialog exists at the time this method is called,482	 * an error is raised. See {@link keys} for information on valid keys arguments.483	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/alert_text484	 *485	 * @property {function():PromisedWebDriver} acceptAlert486	 * Accepts the currently displayed dialog. Usually equivalent to clicking the 'OK' button. If no dialog exists487	 * at the time this method is called, an error is raised.488	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/accept_alert489	 *490	 * @property {function():PromisedWebDriver} dismissAlert491	 * Dismisses the currently displayed dialog. Equivalent to clicking the 'Cancel' button on confirm and prompt492	 * dialogs, and the 'OK' button on alert dialogs. If no dialog exists at the time this method is called, an error493	 * is raised.494	 *495	 * @property {function():PromisedWebDriver -> Element} active496	 * Retrieves the currently focused element.497	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/active498	 *499	 * @property {function():PromisedWebDriver -> string} url500	 * Retrieves the current browser URL.501	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/url502	 *503	 * @property {function():PromisedWebDriver -> Array.<{ name:string, value:string, =path:string, =domain:string, =secure:string, =expiry:string }>} allCookies504	 * Retrieves all cookies set on the current page.505	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/cookie506	 *507	 * @property {function(cookie:{ name:string, value:string, =path:string, =domain:string, =secure:string, =expiry:string }):PromisedWebDriver} setCookie508	 * Sets a cookie for the current page.509	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/cookie510	 *511	 * @property {function():PromisedWebDriver} deleteAllCookies512	 * Deletes all cookies set on the current page.513	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId/cookie514	 *515	 * @property {function(name:string):PromisedWebDriver} deleteCookie516	 * Deletes a cookie with the given name from the current page.517	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId/cookie/:name518	 *519	 * @property {function():PromisedWebDriver -> string} getOrientation520	 * Retrieves the current device orientation. One of 'LANDSCAPE', 'PORTRAIT'.521	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/orientation522	 *523	 * @property {function(orientation:string):PromisedWebDriver} setOrientation524	 * Sets the current device orientation. One of 'LANDSCAPE', 'PORTRAIT'.525	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/orientation526	 *527	 * @property {function(key:string, value:string):PromisedWebDriver} setLocalStorageKey528	 * Sets an item in local storage.529	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/local_storage530	 *531	 * @property {function(key:string):PromisedWebDriver -> string} getLocalStorageKey532	 * Retrieves an item from local storage.533	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/local_storage/key/:key534	 *535	 * @property {function(key:string):PromisedWebDriver} removeLocalStorageKey536	 * Removes an item from local storage.537	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId/local_storage/key/:key538	 *539	 * @property {function():PromisedWebDriver} clearLocalStorage540	 * Removes all data from local storage for the current page.541	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId/local_storage542	 *543	 * @property {function(element:Element=):PromisedWebDriver -> { x:number, y:number }} getLocation544	 * Gets the position of an element on the page. If no element is provided explicitly, the last stored context545	 * element will be used.546	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/location547	 *548	 * @property {function(element:Element=):PromisedWebDriver -> { width:number, height:number }} getSize549	 * Gets the dimensions of an element on the page. If no element is provided explicitly, the last stored context550	 * element will be used.551	 * http://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/element/:id/size552	 *553	 * @property {function():PromisedWebDriver} end554	 * Removes the last element from the stack of stored context elements, just like jQuery's `end` method.555	 * For example:556	 *557	 * <pre>558	 * remote.elementById('foo')559	 *     .elementById('bar')560	 *         // this will click on the element `bar`561	 *         .click()562	 *         // this will stop future methods from interacting on `bar`563	 *         .end()564	 *     // this will click on the element `foo`565	 *     .click()566	 *     // this will stop future methods from interacting on `foo`567	 *     .end();568	 * </pre>569	 *570	 * @property {function(milliseconds:number)} wait571	 * Waits for the given period of time, in milliseconds, before executing the next command.572	 *573	 * @property {function(function(value), function(error:Error)):PromisedWebDriver} then574	 * Standard Promises/A `then` callback registration method. Call this immediately after a method that normally575	 * returns a value to retrieve and interact with the value returned by that call. For example:576	 *577	 * <pre>578	 * remote.elementById('foo')579	 *     .text()580	 *     .then(function (text) {581	 *         // `text` contains the text from the element `foo`582	 *     });583	 * </pre>584	 *585	 * For more information on promises, please see http://dojotoolkit.org/documentation/tutorials/1.9/promises/.586	 *587	 * Note that as of Intern 1.1, attempting to add new commands to the current remote instance from within a `then`588	 * callback will result in a deadlock. This will be addressed in a future version of Intern.589	 *590	 * @property {function(function(error:Error)):PromisedWebDriver} otherwise591	 * Convenience function equivalent to calling `remote.then(null, callback)`.592	 *593	 * @property {function(function(=error:Error)):PromisedWebDriver} always594	 * Convenience function equivalent to calling `remote.then(callback, callback)`.595	 *596	 * @property {function()} cancel597	 * Cancels all outstanding remote requests and rejects the current promise chain.598	 *599	 * @property {function(code:string, timeout:number, =pollFrequency:number):PromisedWebDriver} waitForCondition600	 * Polls the remote browser using `eval` until the code provided in `code` returns a truthy value. If the code does601	 * not evaluate positively within `timeout` milliseconds (default: 1000), an error is raised. An optional602	 * frequency for polling may also be provided (default: 100).603	 *604	 * `waitForConditionInBrowser` should be preferred as long as all browsers under test support the `executeAsync`605	 * method.606	 *607	 * @property {function(code:string, timeout:number, =pollFrequency:number):PromisedWebDriver} waitForConditionInBrowser608	 * Tells the remote browser to poll using `executeAsync` until the code provided in `code` returns a truthy value.609	 * If the code does not evaluate positively within `timeout` milliseconds (default: 1000), an error is raised. An610	 * optional frequency for polling may also be provided (default: 100).611	 *612	 * Note that `executeAsync` may not be supported by all Selenium drivers, in which case `waitForCondition` should613	 * be used instead.614	 *615	 * @property haltChain616	 * Do not use this method. It is not relevant to PromisedWebDriver.617	 * @property pauseChain618	 * Do not use this method. It is not relevant to PromisedWebDriver.619	 * @property chain620	 * Do not use this method. It is not relevant to PromisedWebDriver.621	 * @property next622	 * Do not use this method. It is not relevant to PromisedWebDriver.623	 * @property queueAdd624	 * Do not use this method. It is not relevant to PromisedWebDriver.625	 * @property safeEval626	 * Do not use this method. Use `eval` instead.627	 * @property safeExecute628	 * Do not use this method. Use `execute` instead.629	 * @property safeExecuteAsync630	 * Do not use this method. Use `executeAsync` instead.631	 * @property windowSize632	 * Do not use this method. Use `setWindowSize` instead.633	 * @property altSessionCapabilities634	 * Do not use this method. Use `sessionCapabilities` instead.635	 * @property setHTTPInactivityTimeout636	 * Do not use this method. It is not documented. (It is a timeout for the underlying HTTP request code.)637	 * @property setWaitTimeout638	 * Do not use this method. Use `setImplicitWaitTimeout` instead.639	 * @property element640	 * Do not use this method. Use the more specific `elementBy*` methods instead.641	 * @property elementOrNull642	 * Do not use this method. Use the more specific `elementBy*IfExists` methods instead.643	 * @property elementIfExists644	 * Do not use this method. Use the more specific `elementBy*IfExists` methods instead.645	 * @property elements646	 * Do not use this method. Use the more specific `elementsBy*` methods instead.647	 * @property hasElement648	 * Do not use this method. Use the `elementBy*IfExists` methods instead.649	 * @property waitForElement650	 * Do not use this method. Set `setImplicitWaitTimeout` and use the `elementBy*` methods instead.651	 * @property waitForVisible652	 * Do not use this method. Use the more specific `waitForVisibleBy*` methods instead.653	 * @property *OrNull654	 * Do not use these methods. Use `elementBy*IfExists` instead.655	 * @property hasElement*656	 * Do not use these methods. Set `setImplicitWaitTimeout` and use the `elementBy*` methods instead.657	 * @property waitForElement*658	 * Do not use these methods. Set `setImplicitWaitTimeout` and use the `elementBy*` methods instead.659	 * @property *ByCss660	 * Do not use these methods. Use the `*ByCssSelector` methods instead.661	 * @property displayed662	 * Do not use this method. Use `isDisplayed` instead.663	 * @property enabled664	 * Do not use this method. Use `isEnabled` instead.665	 * @property getValue666	 * Do not use this method. Use `getAttribute('value')` instead.667	 * @property getComputedCSS668	 * Do not use this method. Use `getComputedCss` instead.669	 * @property textPresent670	 * Do not use this method. Use `text` instead.671	 * @property isVisible672	 * Do not use this method. Use `isDisplayed` instead.673	 * @property getPageIndex674	 * Do not use this method. It is not documented.675	 */676	function PromisedWebDriver(config, desiredEnvironment) {677		this._wd = wd.remote(config);678		this._desiredEnvironment = desiredEnvironment;679		this._context = [];680	}681	// WebDriver.prototype exposes all method names, including element methods, except for the 'equals' element682	// method683	// TODO: Do not expose methods that are marked as "Do not use" in the documentation above, then remove the684	// documentation.685	Object.keys(WebDriver.prototype).concat([ 'equals' ]).forEach(function (key) {686		// The original object is indirectly extended by adapting individual methods in order to ensure that any687		// calls by the original WebDriver object to its own methods are not broken by an unexpectedly different688		// interface689		var wrappedFunction = util.adapt(WebDriver.prototype[key], '_wd');690		// Upgrade init so that it can be called with no arguments and use desired environment data provided by691		// the constructor692		if (key === 'init') {693			wrappedFunction = (function (wrappedFunction) {694				return function (desiredEnvironment) {695					return wrappedFunction.call(this, desiredEnvironment || this._desiredEnvironment);696				};697			})(wrappedFunction);698		}699		// Always retrieve code coverage data before navigating to a new URL700		else if (key === 'get' || key === 'quit') {701			wrappedFunction = (function (wrappedFunction) {702				return function () {703					var self = this,704						args = Array.prototype.slice.call(arguments, 0);705					// If someone uses require.toUrl with a functional test, the path will be an absolute filesystem706					// path to the file, but it needs to be a URL to the proxy to work on the remote system707					if (key === 'get' && !/^https?:/.test(args[0])) {708						// oh also by the way baseUrl might not be normalized ha ha ha ha.709						args[0] = this.proxyUrl + args[0].slice(pathUtils.normalize(global.require.baseUrl).length);710					}711					var dfd = new Deferred();712					// Since we are in the middle of a chained call, we must do a low-level call to the wd object;713					// if we try to just call PromisedWebDriver methods directly, the chain will be stalled permanently714					// waiting for the `get` call to complete because the PWD methods cannot run until `get` completes715					// but `get` will not be able to complete without the subsequent PWD methods716					this._wd.execute('return typeof __internCoverage !== "undefined" && JSON.stringify(__internCoverage)', function (error, returnValue) {717						if (error) {718							dfd.reject(error);719							return;720						}721						// returnValue might be falsy on a page with no coverage data, so don't try to publish coverage722						// results to prevent things from breaking723						returnValue && topic.publish('/coverage', self.sessionId, JSON.parse(returnValue));724						wrappedFunction.apply(self, args).then(dfd.resolve.bind(dfd), dfd.reject.bind(dfd));725					});726					return dfd.promise;727				};728			})(wrappedFunction);729		}730		// Allow real functions to be passed directly to execute731		else if (key === 'execute' || key === 'safeExecute') {732			wrappedFunction = (function (wrappedFunction) {733				return function () {734					var args = Array.prototype.slice.call(arguments, 0);735					if (typeof args[0] === 'function') {736						args[0] = 'return (' + args[0] + ').apply(this, arguments);';737					}738					return wrappedFunction.apply(this, args);739				};740			})(wrappedFunction);741		}742		if (/* not a private interface */ key.charAt(0) !== '_') {743			PromisedWebDriver.prototype[key] = function () {744				var self = this,745					args = Array.prototype.slice.call(arguments, 0);746				this._lastPromise = when(this._lastPromise).then(function () {747					// Methods that might interact on elements should be modified to use the current context element748					// as the context object749					if (elementContextMethods[key] && self._context.length) {750						self = self._context[self._context.length - 1];751						wrappedFunction = util.adapt(self[key]);752					}753					// Methods that might accept an element argument should be modified to use the current context754					// element as the argument755					else if (elementArgumentMethods[key] && self._context.length) {756						args.unshift(self._context[self._context.length - 1]);757					}758					return wrappedFunction.apply(self, args);759				});760				this._lastPromise = this._lastPromise.then(function (lastReturnValue) {761					// Methods that get elements need to provide the element as context for the next call to the fluid762					// interface, so users can type e.g. `remote.elementById('foo').clickElement()` and it works as763					// expected.764					if (lastReturnValue instanceof Element) {765						self._context.push(lastReturnValue);766					}767					// We should also check to see if a DOM element is returned from remote execution, e.g. `execute`768					// or `safeExecute`. If this is the case, we should use this element as the context for the next769					//  call to maintain the fluid interface described above.770					else if (lastReturnValue && lastReturnValue.ELEMENT) {771						lastReturnValue = new Element(lastReturnValue.ELEMENT, self._wd);772						self._context.push(lastReturnValue);773					}774					return lastReturnValue;775				});776				return this;777			};778		}779	});780	/**781	 * Ends a context chain.782	 * @param {=number} numContextsToPop The number of element contexts to pop. Defaults to 1.783	 */784	PromisedWebDriver.prototype.end = function (numContextsToPop) {785		var self = this;786		this._lastPromise = when(this._lastPromise).then(function (value) {787			numContextsToPop = numContextsToPop || 1;788			while (numContextsToPop-- && self._context.length) {789				self._context.pop();790			}791			return value;792		});793		return this;794	};795	/**796	 * Waits milliseconds before performing the next command.797	 * @param {number} waitMs Milliseconds to wait.798	 */799	PromisedWebDriver.prototype.wait = function (waitMs) {800		this._lastPromise = when(this._lastPromise).then(function () {801			var dfd = new Deferred();802			setTimeout(function () {803				dfd.resolve();804			}, waitMs);805			return dfd.promise;806		});807		return this;808	};809	PromisedWebDriver.prototype.then = function (callback, errback) {810		var self = this,811			dfd = new Deferred();812		function fixCallback(callback) {813			if (typeof callback !== 'function') {814				return callback;815			}816			return function () {817				self._lastPromise = undefined;818				try {819					var returnValue = callback.apply(this, arguments);820					when(self._lastPromise || returnValue).then(function () {821						dfd.resolve(returnValue);822					}, function (error) {823						dfd.reject(error);824					});825				}826				catch (error) {827					dfd.reject(error);828				}829				return dfd.promise;830			};831		}832		this._lastPromise = this._lastPromise.then(fixCallback(callback), fixCallback(errback));833		return this;834	};835	PromisedWebDriver.prototype.otherwise = function (errback) {836		return this.then(null, errback);837	};838	PromisedWebDriver.prototype.always = function (callback) {839		return this.then(callback, callback);840	};841	/**842	 * Cancels the execution of the remaining chain of commands for this driver.843	 */844	PromisedWebDriver.prototype.cancel = function () {845		this._lastPromise && this._lastPromise.cancel.apply(this._lastPromise, arguments);846		return this;847	};848	/**849	 * Cancels the execution of the remaining chain of commands for this driver and dereferences the old promise chain.850	 */851	PromisedWebDriver.prototype.reset = function () {852		this.cancel();853		this._lastPromise = undefined;854		this._context = [];855		return this;856	};857	/**858	 * Sends a no-op command to the remote server on an interval to prevent.859	 *860	 * @param delay861	 * Amount of time to wait between heartbeats.862	 */863	PromisedWebDriver.prototype.setHeartbeatInterval = function (/**number*/ delay) {864		this._heartbeatIntervalHandle && this._heartbeatIntervalHandle.remove();865		if (delay) {866			// A heartbeat command is sent immediately when the interval is set because it is unknown how long ago867			// the last command was sent and it simplifies the implementation by requiring only one call to868			// `setTimeout`869			var self = this;870			(function sendHeartbeat() {871				var timeoutId,872					cancelled = false,873					startTime = Date.now();874				self._heartbeatIntervalHandle = {875					remove: function () {876						cancelled = true;877						clearTimeout(timeoutId);878					}879				};880				// The underlying `wd` object is accessed directly to bypass pending commands on the promise chain.881				// `url` is used because some more appropriate meta-commands like `status` do not prevent Sauce Labs882				// from timing out883				self._wd.url(function () {884					if (!cancelled) {885						timeoutId = setTimeout(sendHeartbeat, delay - (Date.now() - startTime));886					}887				});888			})();889		}890	};891	/**892	 * This interface provides a mechanism for creating a remote WebDriver instance that uses Promises/A instead of893	 * Node.js callbacks to provide more expressive tests.894	 */895	return {896		/**897		 * Creates a new Promises/A-based remote WebDriver instance.898		 *899		 * @param {{ host: string, port: number, username: ?string, accessKey: ?string }} config900		 * Configuration for connection to the remote WebDriver server. The username and accessKey keys are used901		 * for integration with Sauce Labs.902		 * @returns {PromisedWebDriver}903		 */904		remote: function (config, desiredEnvironment) {905			return new PromisedWebDriver(config, desiredEnvironment);906		}907	};...

Full Screen

Full Screen

EyesWDIOUtils.js

Source:EyesWDIOUtils.js Github

copy

Full Screen

1"use strict";2const {EyesJsBrowserUtils, Location, ArgumentGuard, RectangleSize} = require('@applitools/eyes-sdk-core');3const EyesDriverOperationError = require('./errors/EyesDriverOperationError');4const ImageOrientationHandler = require('./ImageOrientationHandler');5const JavascriptHandler = require('./JavascriptHandler');6/*7 ---8 name: EyesWDIOUtils9 description: Handles browser related functionality.10 ---11 */12let imageOrientationHandler = new class ImageOrientationHandlerImpl extends ImageOrientationHandler {13  /** @override */14  async isLandscapeOrientation(driver) {15    try {16      const orientation = await driver.remoteWebDriver.getOrientation();17      return orientation === 'landscape';18    } catch (e) {19      throw new EyesDriverOperationError("Failed to get orientation!", e);20    }21  }22  /** @override */23  async tryAutomaticRotation(logger, driver, image) {24    return 0;25  }26}();27// noinspection JSUnusedLocalSymbols28let javascriptHandler = new class JavascriptHandlerImpl extends JavascriptHandler {29}();30class EyesWDIOUtils {31  /**32   * @param {ImageOrientationHandler} value33   */34  static setImageOrientationHandlerHandler(value) {35    imageOrientationHandler = value;36  }37  /**38   * @param {WebDriver} driver The driver for which to check the orientation.39   * @return {Promise<boolean>} {@code true} if this is a mobile device and is in landscape orientation. {@code40   *   false} otherwise.41   */42  static async isLandscapeOrientation(driver) {43    if (EyesWDIOUtils.isMobileDevice(driver)) {44      return imageOrientationHandler.isLandscapeOrientation(driver);45    } else {46      return false;47    }48  }49  /**50   * @param {Logger} logger51   * @param {WebDriver} driver52   * @param {MutableImage} image53   * @return {Promise<number>}54   */55  static tryAutomaticRotation(logger, driver, image) {56    return imageOrientationHandler.tryAutomaticRotation(logger, driver, image);57  }58  /**59   * @param {JavascriptHandler} handler60   */61  static setJavascriptHandler(handler) {62    javascriptHandler = handler;63  }64  /**65   * @param {string} script66   * @param {object...} args67   */68  static handleSpecialCommands(script, ...args) {69    return javascriptHandler.handle(script, ...args);70  }71  /**72   * @private73   * @type {string}74   */75  static get JS_GET_VIEWPORT_SIZE() {76    return `77      var height = undefined;78      var width = undefined;79      if (window.innerHeight) {80        height = window.innerHeight;81      } else if (document.documentElement && document.documentElement.clientHeight) {82        height = document.documentElement.clientHeight;83      } else {84        var b = document.getElementsByTagName('body')[0];85        if (b.clientHeight) {86          height = b.clientHeight;87        }88      }89      if (window.innerWidth) {90        width = window.innerWidth;91      } else if (document.documentElement && document.documentElement.clientWidth) {92        width = document.documentElement.clientWidth;93      } else {94        var b = document.getElementsByTagName('body')[0];95        if (b.clientWidth) {96          width = b.clientWidth;97        }98      }99      return [width, height];100    `;101  }102  /**103   * @private104   * @type {string}105   */106  static get JS_GET_CURRENT_SCROLL_POSITION() {107    return "var doc = document.documentElement; " +108      "var x = window.scrollX || ((window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0)); " +109      "var y = window.scrollY || ((window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)); " +110      "return [x, y];";111  }112  /**113   * @private114   * @type {string}115   */116  static get JS_GET_CONTENT_ENTIRE_SIZE() {117    return `var scrollWidth = document.documentElement.scrollWidth;118      var bodyScrollWidth = document.body.scrollWidth; 119      var totalWidth = Math.max(scrollWidth, bodyScrollWidth); 120      var clientHeight = document.documentElement.clientHeight;121      var bodyClientHeight = document.body.clientHeight; 122      var scrollHeight = document.documentElement.scrollHeight;123      var bodyScrollHeight = document.body.scrollHeight;124      var maxDocElementHeight = Math.max(clientHeight, scrollHeight);125      var maxBodyHeight = Math.max(bodyClientHeight, bodyScrollHeight);126      var totalHeight = Math.max(maxDocElementHeight, maxBodyHeight);127      return [totalWidth, totalHeight];`;128  }129  /**130   * @return {string}131   */132  static get JS_GET_IS_BODY_OVERFLOW_HIDDEN() {133    return "var styles = window.getComputedStyle(document.body, null);" +134      "var overflow = styles.getPropertyValue('overflow');" +135      "var overflowX = styles.getPropertyValue('overflow-x');" +136      "var overflowY = styles.getPropertyValue('overflow-y');" +137      "return overflow == 'hidden' || overflowX == 'hidden' || overflowY == 'hidden'";138  }139// IMPORTANT: Notice there's a major difference between scrollWidth and scrollHeight.140// While scrollWidth is the maximum between an element's width and its content width,141// scrollHeight might be smaller (!) than the clientHeight, which is why we take the maximum between them.142  static get JS_COMPUTE_CONTENT_ENTIRE_SIZE() {143    return "var scrollWidth = document.documentElement.scrollWidth; " +144      "var bodyScrollWidth = document.body.scrollWidth; " +145      "var totalWidth = Math.max(scrollWidth, bodyScrollWidth); " +146      "var clientHeight = document.documentElement.clientHeight; " +147      "var bodyClientHeight = document.body.clientHeight; " +148      "var scrollHeight = document.documentElement.scrollHeight; " +149      "var bodyScrollHeight = document.body.scrollHeight; " +150      "var maxDocElementHeight = Math.max(clientHeight, scrollHeight); " +151      "var maxBodyHeight = Math.max(bodyClientHeight, bodyScrollHeight); " +152      "var totalHeight = Math.max(maxDocElementHeight, maxBodyHeight); ";153  }154  // noinspection JSUnusedGlobalSymbols155  static get JS_RETURN_CONTENT_ENTIRE_SIZE() {156    return EyesWDIOUtils.JS_COMPUTE_CONTENT_ENTIRE_SIZE + "return [totalWidth, totalHeight];";157  }158  static get JS_SCROLL_TO_BOTTOM_RIGHT() {159    return EyesWDIOUtils.JS_COMPUTE_CONTENT_ENTIRE_SIZE + "window.scrollTo(totalWidth, totalHeight);";160  }161  /**162   * @private163   * @type {string[]}164   */165  static get JS_TRANSFORM_KEYS() {166    return ["transform", "-webkit-transform"];167  }168  /**169   * Gets the device pixel ratio.170   *171   * @param {EyesJsExecutor} executor The executor to use.172   * @return {Promise<number>} A promise which resolves to the device pixel ratio (float type).173   */174  static async getDevicePixelRatio(executor) {175    const result = await executor.executeScript('return window.devicePixelRatio');176    return parseFloat(result);177  }178  /**179   * Get the current transform of page.180   *181   * @param {EyesJsExecutor} executor The executor to use.182   * @return {Promise.<Object.<String, String>>} A promise which resolves to the current transform value.183   */184  static async getCurrentTransform(executor) {185    let script = "return { ";186    for (let i = 0, l = EyesWDIOUtils.JS_TRANSFORM_KEYS.length; i < l; i++) {187      script += `'${EyesWDIOUtils.JS_TRANSFORM_KEYS[i]}': document.documentElement.style['${EyesWDIOUtils.JS_TRANSFORM_KEYS[i]}'],`;188    }189    script += " }";190    return await executor.executeScript(script);191  }192  static JS_GET_TRANSFORM_VALUE(element, key) {193    return `${element}.style['${key}']`;194  }195  static JS_SET_TRANSFORM_VALUE(element, key, value) {196    return `${element}.style['${key}'] = '${value}'`;197  }198  static getCurrentElementTransforms(executor, element) {199    let script = "return { ";200    for (let i = 0, l = EyesWDIOUtils.JS_TRANSFORM_KEYS.length; i < l; i++) {201      const tk = EyesWDIOUtils.JS_TRANSFORM_KEYS[i];202      script += `'${tk}': ${EyesWDIOUtils.JS_GET_TRANSFORM_VALUE('arguments[0]', tk)},`;203    }204    script += " }";205    return executor.executeScript(script, element);206  }207  /**208   * @param {WDIOJSExecutor} executor209   * @param {Promise.<WebElement>} webElementPromise210   * @param transform211   * @return {*|Promise}212   */213  static async setElementTransforms(executor, webElementPromise, transform) {214    let script = '';215    for (let i = 0, l = EyesWDIOUtils.JS_TRANSFORM_KEYS.length; i < l; i++) {216      const tk = EyesWDIOUtils.JS_TRANSFORM_KEYS[i];217      script += `${EyesWDIOUtils.JS_SET_TRANSFORM_VALUE('arguments[0]', tk, transform)};`;218      // script += `${EyesWDIOUtils.JS_SET_TRANSFORM_VALUE("document.getElementsByTagName('img')[0]", tk, transform)};`;219    }220    const webElement = await webElementPromise;221    return executor.executeScript(script, webElement.element);222  }223  /**224   * Sets transforms for document.documentElement according to the given map of style keys and values.225   *226   * @param {EyesJsExecutor} executor The executor to use.227   * @param {Object.<String, String>} transforms The transforms to set. Keys are used as style keys and values are the values for those styles.228   * @return {Promise}229   */230  static setTransforms(executor, transforms) {231    let script = '';232    for (const key in transforms) {233      if (transforms.hasOwnProperty(key)) {234        script += `document.documentElement.style['${key}'] = '${transforms[key]}';`;235      }236    }237    return executor.executeScript(script);238  }239  /**240   * Set the given transform to document.documentElement for all style keys defined in {@link JS_TRANSFORM_KEYS}241   *242   * @param {EyesJsExecutor} executor The executor to use.243   * @param {String} transform The transform to set.244   * @return {Promise<void>} A promise which resolves to the previous transform once the updated transform is set.245   */246  static setTransform(executor, transform) {247    const transforms = {};248    if (!transform) {249      transform = '';250    }251    for (let transformKey of EyesWDIOUtils.JS_TRANSFORM_KEYS) {252      transforms[transformKey] = transform;253    }254    return EyesWDIOUtils.setTransforms(executor, transforms);255  }256  /**257   * CSS translate the document to a given location.258   *259   * @param {EyesJsExecutor} executor The executor to use.260   * @param {Location} position The position to translate to.261   * @return {Promise} A promise which resolves to the previous transform when the scroll is executed.262   */263  static async translateTo(executor, position) {264    await EyesWDIOUtils.setTransform(executor, `translate(10px, -${position.getY()}px)`);265    return EyesWDIOUtils.setTransform(executor, `translate(-${position.getX()}px, -${position.getY()}px)`);266  }267  /**268   *269   * @param {WDIOJSExecutor} executor270   * @param {Promise.<WebElement>} webElementPromise271   * @param {Location} position272   * @return {*}273   */274  static elementTranslateTo(executor, webElementPromise, position) {275    return EyesWDIOUtils.setElementTransforms(executor, webElementPromise, `translate(${position.getX()}px, ${position.getY()}px)`);276  }277  /**278   * Gets the current scroll position.279   *280   * @param {EyesJsExecutor} executor The executor to use.281   * @return {Promise.<Location>} The current scroll position of the current frame.282   */283  static async getCurrentScrollPosition(executor) {284    const value = await executor.executeScript(EyesWDIOUtils.JS_GET_CURRENT_SCROLL_POSITION);285    // If we can't find the current scroll position, we use 0 as default.286    return new Location(Math.ceil(value[0]) || 0, Math.ceil(value[1]) || 0);287  }288  /**289   * Get the entire page size.290   *291   * @param {EyesJsExecutor} executor The executor to use.292   * @return {RectangleSize} A promise which resolves to an object containing the width/height of the page.293   */294  static async getCurrentFrameContentEntireSize(executor) {295    // IMPORTANT: Notice there's a major difference between scrollWidth and scrollHeight.296    // While scrollWidth is the maximum between an element's width and its content width,297    // scrollHeight might be smaller (!) than the clientHeight, which is why we take the maximum between them.298    try {299      const value = await executor.executeScript(EyesWDIOUtils.JS_GET_CONTENT_ENTIRE_SIZE);300      return new RectangleSize(parseInt(value[0], 10) || 0, parseInt(value[1], 10) || 0);301    } catch (e) {302      throw new EyesDriverOperationError("Failed to extract entire size!", e);303    }304  }305  /**306   * Sets the overflow of the current context's document element.307   *308   * @param {EyesJsExecutor} executor - The executor to use.309   * @param {?string} value - The overflow value to set.310   * @param {WebElement} [scrollbarsRoot]311   * @return {Promise<string>} - The previous value of overflow (could be {@code null} if undefined).312   */313  static setOverflow(executor, value, scrollbarsRoot) {314    return EyesJsBrowserUtils.setOverflow(executor, value, scrollbarsRoot);315  }316  // noinspection JSUnusedGlobalSymbols317  /**318   * @param {EyesJsExecutor} executor The executor to use.319   * @return {Promise.<Boolean>} A promise which resolves to the {@code true} if body overflow is hidden, {@code false} otherwise.320   */321  static isBodyOverflowHidden(executor) {322    try {323      return executor.executeScript(EyesWDIOUtils.JS_GET_IS_BODY_OVERFLOW_HIDDEN);324    } catch (e) {325      throw new EyesDriverOperationError('Failed to get state of body overflow', e);326    }327  }328  // noinspection JSUnusedGlobalSymbols329  /**330   * Updates the document's body "overflow" value331   *332   * @param {EyesJsExecutor} executor The executor to use.333   * @param {String} overflowValue The values of the overflow to set.334   * @return {Promise.<String>} A promise which resolves to the original overflow of the document.335   */336  static setBodyOverflow(executor, overflowValue) {337    let script;338    if (overflowValue === null) {339      script =340        "var origOverflow = document.body.style.overflow; " +341        "document.body.style.overflow = undefined; " +342        "return origOverflow";343    } else {344      script =345        "var origOverflow = document.body.style.overflow; " +346        "document.body.style.overflow = \"" + overflowValue + "\"; " +347        "return origOverflow";348    }349    try {350      return executor.executeScript(script);351    } catch (e) {352      throw new EyesDriverOperationError('Failed to set body overflow', e);353    }354  }355  /**356   * Hides the scrollbars of the current context's document element.357   *358   * @param {EyesJsExecutor} executor The executor to use.359   * @param {int} stabilizationTimeout The amount of time to wait for the "hide scrollbars" action to take effect (Milliseconds). Zero/negative values are ignored.360   * @param {WebElement} scrollbarsRoot361   * @return {Promise.<String>} The previous value of the overflow property (could be {@code null}).362   */363  static async hideScrollbars(executor, stabilizationTimeout, scrollbarsRoot) {364    const res = await EyesJsBrowserUtils.setOverflow(executor, 'hidden', scrollbarsRoot);365    if (stabilizationTimeout > 0) {366      await executor.sleep(stabilizationTimeout);367      return res;368    } else {369      return res;370    }371  }372  /**373   * Tries to get the viewport size using Javascript. If fails, gets the entire browser window size!374   *375   * @param {EyesJsExecutor} executor The executor to use.376   * @return {RectangleSize} The viewport size.377   */378  static async getViewportSize(executor) {379    const value = await executor.executeScript(EyesWDIOUtils.JS_GET_VIEWPORT_SIZE);380    // await browser.getViewportSize()381    return new RectangleSize(parseInt(value[0], 10) || 0, parseInt(value[1], 10) || 0);382  }383  /**384   * @param {Logger} logger385   * @param {EyesJsExecutor} executor The executor to use.386   * @return {Promise.<RectangleSize>} The viewport size of the current context, or the display size if the viewport size cannot be retrieved.387   */388  static async getViewportSizeOrDisplaySize(logger, executor) {389    logger.verbose("getViewportSizeOrDisplaySize()");390    if (!EyesWDIOUtils.isMobileDevice(executor.remoteWebDriver)) {391      try {392        return await EyesWDIOUtils.getViewportSize(executor);393      } catch (e) {394        logger.verbose("Failed to extract viewport size using Javascript:", e);395      }396    }397    // If we failed to extract the viewport size using JS, will use the window size instead.398    logger.verbose("Using window size as viewport size.");399    /** {width:number, height:number} */400    let {width, height} = await EyesWDIOUtils.getWindowRect(executor);401    try {402      const result = await EyesWDIOUtils.isLandscapeOrientation(executor);403      if (result && height > width) {404        const temp = width;405        // noinspection JSSuspiciousNameCombination406        width = height;407        height = temp;408      }409    } catch (ignored) {410      // Not every WebDriver supports querying for orientation.411    }412    logger.verbose(`Done! Size ${width} x ${height}`);413    return new RectangleSize(width, height);414  }415  /**416   * @param {Logger} logger417   * @param {EyesWebDriver} browser The browser to use.418   * @param {RectangleSize} requiredSize The size to set419   * @return {Promise<boolean>}420   */421  static async setBrowserSize(logger, browser, requiredSize) {422    try {423      await EyesWDIOUtils._setBrowserSizeLoop(logger, browser, requiredSize);424      return true;425    } catch (ignored) {426      return false;427    }428  }429  /**430   * Sets the scroll position of the current frame.431   *432   * @param {EyesJsExecutor} executor The executor to use.433   * @param {Location} location Location to scroll to434   * @return {Promise} A promise which resolves after the action is performed and timeout passed.435   */436  static setCurrentScrollPosition(executor, location) {437    return executor.executeScript(`window.scrollTo(${location.getY()}, ${location.getY()})`);438  }439  /**440   * @param {Logger} logger441   * @param {EyesWebDriver} browser The browser to use.442   * @param {RectangleSize} requiredSize The size to set443   * @param {number} sleep444   * @param {number} retries445   * @return {Promise<boolean>}446   */447  static async _setBrowserSizeLoop(logger, browser, requiredSize, sleep = 1000, retries = 3) {448    logger.verbose("Trying to set browser size to:", requiredSize);449    await browser.remoteWebDriver.setWindowSize(requiredSize.getWidth(), requiredSize.getHeight());450    let size = await EyesWDIOUtils.getWindowRect(browser);451    const currentSize = new RectangleSize(size.width, size.height);452    logger.log(`Current browser size: ${currentSize}`);453    if (currentSize.equals(requiredSize)) {454      return true;455    }456    if (retries === 0) {457      logger.verbose('Failed to set browser size: retries is out.');458      return false;459    }460    return EyesWDIOUtils._setBrowserSizeLoop(logger, browser, requiredSize, sleep, retries - 1);461  }462  /**463   * @param {Logger} logger464   * @param {EyesWebDriver} browser The browser to use.465   * @param {RectangleSize} actualViewportSize466   * @param {RectangleSize} requiredViewportSize467   * @return {Promise<boolean>}468   */469  static async setBrowserSizeByViewportSize(logger, browser, actualViewportSize, requiredViewportSize) {470    /** {width:number, height:number} */471    let browserSize = await EyesWDIOUtils.getWindowRect(browser);472    logger.verbose("Current browser size:", browserSize);473    const requiredBrowserSize = {474      width: browserSize.width + (requiredViewportSize.getWidth() - actualViewportSize.getWidth()),475      height: browserSize.height + (requiredViewportSize.getHeight() - actualViewportSize.getHeight())476    };477    return EyesWDIOUtils.setBrowserSize(logger, browser, new RectangleSize(requiredBrowserSize));478  }479  /**480   * Tries to set the viewport481   *482   * @param {Logger} logger483   * @param {EyesWebDriver} browser The browser to use.484   * @param {RectangleSize} requiredSize The viewport size.485   * @returns {Promise<boolean>}486   */487  static async setViewportSize(logger, browser, requiredSize) {488    ArgumentGuard.notNull(requiredSize, "requiredSize");489    // First we will set the window size to the required size.490    // Then we'll check the viewport size and increase the window size accordingly.491    logger.verbose("setViewportSize(", requiredSize, ")");492    let jsExecutor = browser.eyes.jsExecutor;493    /** RectangleSize */494    let actualViewportSize = await EyesWDIOUtils.getViewportSize(jsExecutor);495    logger.verbose("Initial viewport size:", actualViewportSize);496    // If the viewport size is already the required size497    if (actualViewportSize.equals(requiredSize)) {498      return true;499    }500    // We move the window to (0,0) to have the best chance to be able to501    // set the viewport size as requested.502    try {503      await browser.remoteWebDriver.setWindowPosition(0, 0);504    } catch (ignored) {505      logger.verbose("Warning: Failed to move the browser window to (0,0)");506    }507    await EyesWDIOUtils.setBrowserSizeByViewportSize(logger, browser, actualViewportSize, requiredSize);508    actualViewportSize = await EyesWDIOUtils.getViewportSize(jsExecutor);509    if (actualViewportSize.equals(requiredSize)) {510      return true;511    }512    // Additional attempt. This Solves the "maximized browser" bug513    // (border size for maximized browser sometimes different than non-maximized, so the original browser size calculation is wrong).514    logger.verbose("Trying workaround for maximization...");515    await EyesWDIOUtils.setBrowserSizeByViewportSize(logger, browser, actualViewportSize, requiredSize);516    actualViewportSize = await EyesWDIOUtils.getViewportSize(jsExecutor);517    logger.verbose("Current viewport size:", actualViewportSize);518    if (actualViewportSize.equals(requiredSize)) {519      return true;520    }521    const MAX_DIFF = 3;522    const widthDiff = actualViewportSize.getWidth() - requiredSize.getWidth();523    const widthStep = widthDiff > 0 ? -1 : 1; // -1 for smaller size, 1 for larger524    const heightDiff = actualViewportSize.getHeight() - requiredSize.getHeight();525    const heightStep = heightDiff > 0 ? -1 : 1;526    let browserSize = await EyesWDIOUtils.getWindowRect(browser);527    const currWidthChange = 0;528    const currHeightChange = 0;529    // We try the zoom workaround only if size difference is reasonable.530    if (Math.abs(widthDiff) <= MAX_DIFF && Math.abs(heightDiff) <= MAX_DIFF) {531      logger.verbose("Trying workaround for zoom...");532      const retriesLeft = Math.abs((widthDiff === 0 ? 1 : widthDiff) * (heightDiff === 0 ? 1 : heightDiff)) * 2;533      const lastRequiredBrowserSize = null;534      return EyesWDIOUtils._setViewportSizeLoop(logger, browser, requiredSize, actualViewportSize, browserSize,535        widthDiff, widthStep, heightDiff, heightStep, currWidthChange, currHeightChange,536        retriesLeft, lastRequiredBrowserSize);537    } else {538      throw new Error("Failed to set viewport size!");539    }540  }541  /**542   * @private543   * @param {Logger} logger544   * @param {EyesWebDriver} browser545   * @param {RectangleSize} requiredSize546   * @param actualViewportSize547   * @param browserSize548   * @param widthDiff549   * @param widthStep550   * @param heightDiff551   * @param heightStep552   * @param currWidthChange553   * @param currHeightChange554   * @param retriesLeft555   * @param {RectangleSize} lastRequiredBrowserSize556   * @return {Promise<boolean>}557   */558  static async _setViewportSizeLoop(logger,559                                    browser,560                                    requiredSize,561                                    actualViewportSize,562                                    browserSize,563                                    widthDiff,564                                    widthStep,565                                    heightDiff,566                                    heightStep,567                                    currWidthChange,568                                    currHeightChange,569                                    retriesLeft,570                                    lastRequiredBrowserSize) {571    logger.verbose("Retries left: " + retriesLeft);572    // We specifically use "<=" (and not "<"), so to give an extra resize attempt573    // in addition to reaching the diff, due to floating point issues.574    if (Math.abs(currWidthChange) <= Math.abs(widthDiff) && actualViewportSize.getWidth() !== requiredSize.getWidth()) {575      currWidthChange += widthStep;576    }577    if (Math.abs(currHeightChange) <= Math.abs(heightDiff) && actualViewportSize.getHeight() !== requiredSize.getHeight()) {578      currHeightChange += heightStep;579    }580    const requiredBrowserSize = new RectangleSize(browserSize.width + currWidthChange, browserSize.height + currHeightChange);581    if (lastRequiredBrowserSize && requiredBrowserSize.equals(lastRequiredBrowserSize)) {582      logger.verbose("Browser size is as required but viewport size does not match!");583      logger.verbose("Browser size: " + requiredBrowserSize + " , Viewport size: " + actualViewportSize);584      logger.verbose("Stopping viewport size attempts.");585      return true;586    }587    await EyesWDIOUtils.setBrowserSize(logger, browser, requiredBrowserSize);588    lastRequiredBrowserSize = requiredBrowserSize;589    actualViewportSize = await EyesWDIOUtils.getViewportSize(browser.eyes.jsExecutor);590    logger.verbose("Current viewport size (loop):", actualViewportSize);591    if (actualViewportSize.equals(requiredSize)) {592      return true;593    }594    if ((Math.abs(currWidthChange) <= Math.abs(widthDiff) || Math.abs(currHeightChange) <= Math.abs(heightDiff)) && (--retriesLeft > 0)) {595      return EyesWDIOUtils._setViewportSizeLoop(logger, browser, requiredSize, actualViewportSize, browserSize,596        widthDiff, widthStep, heightDiff, heightStep, currWidthChange, currHeightChange,597        retriesLeft, lastRequiredBrowserSize);598    }599    throw new Error("EyesError: failed to set window size! Zoom workaround failed.");600  }601  /**602   * Scrolls current frame to its bottom right.603   *604   * @param {EyesJsExecutor} executor The executor to use.605   * @return {Promise} A promise which resolves after the action is performed and timeout passed.606   */607  static scrollToBottomRight(executor) {608    return executor.executeScript(EyesWDIOUtils.JS_SCROLL_TO_BOTTOM_RIGHT);609  }610  /**611   * @param driver612   * @return {boolean}613   */614  static isMobileDevice(driver) {615    return !!(driver && driver.isMobile && !driver.capabilities.browserName);616  }617  /**618   * @private619   */620  static async getWindowRect(browser) {621    let browserSize;622    try {623      browserSize = await browser.remoteWebDriver.getWindowSize();624    } catch (ignored) {625      browserSize = await browser.remoteWebDriver.getWindowRect();626    }627    return browserSize;628  }629}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...79                  height: 48080            });81      });82      it("set window position", function () {83            return driver.setWindowPosition(0, 0).getWindowPosition().should.become({84                  x: 0,85                  y: 086            });87      });88      it("window position", function () {89            return driver.getWindowPosition().should.become({90                  x: 0,91                  y: 092            });93      });94      it("window size", function () {95            return driver.getWindowSize().should.become({96                  width: 320,97                  height: 480...

Full Screen

Full Screen

websampler.js

Source:websampler.js Github

copy

Full Screen

...25    await super.start();26    if (this.rect) {27      let handle = await this.driver.windowHandle();28      await this.driver.setWindowSize(this.rect.width, this.rect.height, handle);29      await this.driver.setWindowPosition(this.rect.x, this.rect.y, handle);30    }31    await this.driver.get(`${SAMPLER_HOST}/${this.endpoint}`);32    await this.findSamplesFromScoreAnalysis();33    //await this.playNote('{00-silence}');34    await Promise.delay(1000);35  }36  async findSamples (samples) {37    //samples.push('00-silence');38    for (let sample of _.uniq(samples)) {39      if (sample === 'r') continue;40      console.log(`Finding position of ${sample}...`);41      let el = await this.driver.elementById(sample);42      let loc = await el.getLocation();43      let size = await el.getSize();...

Full Screen

Full Screen

writer.js

Source:writer.js Github

copy

Full Screen

...22    if (this.rect) {23      await Promise.delay(1000);24      let handle = await this.driver.windowHandle();25      await this.driver.setWindowSize(this.rect.width, this.rect.height, handle);26      await this.driver.setWindowPosition(this.rect.x, this.rect.y, handle);27    }28    await this.driver.get(`http://localhost:${this.writerPort}`);29    await this.driver.setImplicitWaitTimeout(10000);30    this.textEl = await this.driver.elementById(this.textElId);31  }32  async writeLyrics (segments, tempo) {33    const beatDur = 60 / tempo;34    const msPerBar = beatDur * 1000 * this.beatsPerMeasure;35    for (let [bars, words] of segments) {36      let start = Date.now();37      let desiredDur = bars * msPerBar;38      let desiredEnd = start + desiredDur;39      if (words) {40        words = words.split(" ");...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { remote } = require('webdriverio');2(async () => {3    const browser = await remote({4        capabilities: {5        }6    });7    await browser.setWindowPosition(100, 200);8    await browser.deleteSession();9})();10const { remote } = require('webdriverio');11(async () => {12    const browser = await remote({13        capabilities: {14        }15    });16    const position = await browser.getWindowPosition();17    console.log(position);18    await browser.deleteSession();19})();20const { remote } = require('webdriverio');21(async () => {22    const browser = await remote({23        capabilities: {24        }25    });26    const size = await browser.getWindowSize();27    console.log(size);28    await browser.deleteSession();29})();30const { remote } = require('webdriverio');31(async () => {32    const browser = await remote({33        capabilities: {34        }35    });36    await browser.setWindowSize(400, 400);37    await browser.deleteSession();38})();39const { remote } = require('webdriverio');40(async () => {41    const browser = await remote({42        capabilities: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();3driver.manage().window().setPosition(0,0).then(function(){4  console.log("Window position has been set");5});6driver.quit();7Recommended Posts: Selenium Webdriver | getScreenshotAs() Method8Selenium Webdriver | get() Method9Selenium Webdriver | getPageSource() Method10Selenium Webdriver | getWindowHandle() Method11Selenium Webdriver | getAllWindowHandles() Method12Selenium Webdriver | switchTo() Method13Selenium Webdriver | getWindowPosition() Method14Selenium Webdriver | getWindowSize() Method15Selenium Webdriver | maximize() Method16Selenium Webdriver | minimize() Method17Selenium Webdriver | setSize() Method18Selenium Webdriver | getTitle() Method19Selenium Webdriver | getCurrentUrl() Method20Selenium Webdriver | getWindowHandles() Method21Selenium Webdriver | switchTo() Method22Selenium Webdriver | get() Method23Selenium Webdriver | getPageSource() Method24Selenium Webdriver | getScreenshotAs() Method25Selenium Webdriver | getCurrentUrl() Method26Selenium Webdriver | getTitle() Method

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.setWindowPosition(0, 0);2var position = driver.getWindowPosition();3driver.setWindowRect(0, 0, 100, 200);4var rect = driver.getWindowRect();5var size = driver.getWindowSize();6driver.setWindowSize(100, 200);7driver.lock();8driver.unlock();9driver.backgroundApp(5);10driver.isAppInstalled('com.example.app');11driver.installApp('C:\\path\\to\\app.apk');12driver.removeApp('com.example.app');13driver.launchApp();14driver.closeApp();15driver.resetApp();16driver.startActivity('com.example.app', 'com.example.app.Activity');17driver.getCurrentActivity();18driver.getDeviceTime();19driver.hideKeyboard();20driver.pressKeyCode(3);21driver.longPressKeyCode(3);22driver.pullFile('/data/local/tmp/file.txt');

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.setWindowPosition(0, 0).then(function () {2    console.log("Window position set");3}, function (err) {4    console.log("Error setting window position: " + err);5});6How to use driver.getWindowSize() method7The driver.getWindowSize() method returns a promise that is resolved with an object containing the width and height of the window. The object has the following format:8{width: 100, height: 200}9driver.getWindowSize().then(function (size) {10    console.log("Window size is: " + JSON.stringify(size));11}, function (err) {12    console.log("Error getting window size: " + err);13});14How to use driver.setWindowSize() method15The driver.setWindowSize() method is used to set the size of the current window. This method has two parameters:16The driver.setWindowSize() method returns a promise that is resolved with an object containing the width and height of the window. The object has the following format:17{width: 100, height: 200}18driver.setWindowSize(100, 200).then(function (size) {19    console.log("Window size set: " + JSON.stringify(size));20}, function (err) {21    console.log("Error setting window size: " + err);22});23How to use driver.getOrientation() method24The driver.getOrientation() method is

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.setWindowPosition(0, 0);2driver.setWindowPosition(0, 0);3driver.set_window_position(0, 0)4driver.set_window_position(0, 0)5driver.setWindowPosition(0, 0);6driver.setWindowPosition(0, 0);7driver.set_window_position(0, 0);8driver.setWindowPosition(0, 0);9driver.setWindowPosition(0, 0)10driver.setWindowPosition(0,

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful