chrome.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. // Licensed to the Software Freedom Conservancy (SFC) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The SFC licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. /**
  18. * @fileoverview Defines a {@linkplain Driver WebDriver} client for the Chrome
  19. * web browser. Before using this module, you must download the latest
  20. * [ChromeDriver release] and ensure it can be found on your system [PATH].
  21. *
  22. * There are three primary classes exported by this module:
  23. *
  24. * 1. {@linkplain ServiceBuilder}: configures the
  25. * {@link selenium-webdriver/remote.DriverService remote.DriverService}
  26. * that manages the [ChromeDriver] child process.
  27. *
  28. * 2. {@linkplain Options}: defines configuration options for each new Chrome
  29. * session, such as which {@linkplain Options#setProxy proxy} to use,
  30. * what {@linkplain Options#addExtensions extensions} to install, or
  31. * what {@linkplain Options#addArguments command-line switches} to use when
  32. * starting the browser.
  33. *
  34. * 3. {@linkplain Driver}: the WebDriver client; each new instance will control
  35. * a unique browser session with a clean user profile (unless otherwise
  36. * configured through the {@link Options} class).
  37. *
  38. * __Headless Chrome__ <a id="headless"></a>
  39. *
  40. * To start Chrome in headless mode, simply call
  41. * {@linkplain Options#headless Options.headless()}. Note, starting in headless
  42. * mode currently also disables GPU acceleration.
  43. *
  44. * let chrome = require('selenium-webdriver/chrome');
  45. * let {Builder} = require('selenium-webdriver');
  46. *
  47. * let driver = new Builder()
  48. * .forBrowser('chrome')
  49. * .setChromeOptions(new chrome.Options().headless())
  50. * .build();
  51. *
  52. * __Customizing the ChromeDriver Server__ <a id="custom-server"></a>
  53. *
  54. * By default, every Chrome session will use a single driver service, which is
  55. * started the first time a {@link Driver} instance is created and terminated
  56. * when this process exits. The default service will inherit its environment
  57. * from the current process and direct all output to /dev/null. You may obtain
  58. * a handle to this default service using
  59. * {@link #getDefaultService getDefaultService()} and change its configuration
  60. * with {@link #setDefaultService setDefaultService()}.
  61. *
  62. * You may also create a {@link Driver} with its own driver service. This is
  63. * useful if you need to capture the server's log output for a specific session:
  64. *
  65. * let chrome = require('selenium-webdriver/chrome');
  66. *
  67. * let service = new chrome.ServiceBuilder()
  68. * .loggingTo('/my/log/file.txt')
  69. * .enableVerboseLogging()
  70. * .build();
  71. *
  72. * let options = new chrome.Options();
  73. * // configure browser options ...
  74. *
  75. * let driver = chrome.Driver.createSession(options, service);
  76. *
  77. * Users should only instantiate the {@link Driver} class directly when they
  78. * need a custom driver service configuration (as shown above). For normal
  79. * operation, users should start Chrome using the
  80. * {@link selenium-webdriver.Builder}.
  81. *
  82. * __Working with Android__ <a id="android"></a>
  83. *
  84. * The [ChromeDriver][android] supports running tests on the Chrome browser as
  85. * well as [WebView apps][webview] starting in Android 4.4 (KitKat). In order to
  86. * work with Android, you must first start the adb
  87. *
  88. * adb start-server
  89. *
  90. * By default, adb will start on port 5037. You may change this port, but this
  91. * will require configuring a [custom server](#custom-server) that will connect
  92. * to adb on the {@linkplain ServiceBuilder#setAdbPort correct port}:
  93. *
  94. * let service = new chrome.ServiceBuilder()
  95. * .setAdbPort(1234)
  96. * build();
  97. * // etc.
  98. *
  99. * The ChromeDriver may be configured to launch Chrome on Android using
  100. * {@link Options#androidChrome()}:
  101. *
  102. * let driver = new Builder()
  103. * .forBrowser('chrome')
  104. * .setChromeOptions(new chrome.Options().androidChrome())
  105. * .build();
  106. *
  107. * Alternatively, you can configure the ChromeDriver to launch an app with a
  108. * Chrome-WebView by setting the {@linkplain Options#androidActivity
  109. * androidActivity} option:
  110. *
  111. * let driver = new Builder()
  112. * .forBrowser('chrome')
  113. * .setChromeOptions(new chrome.Options()
  114. * .androidPackage('com.example')
  115. * .androidActivity('com.example.Activity'))
  116. * .build();
  117. *
  118. * [Refer to the ChromeDriver site] for more information on using the
  119. * [ChromeDriver with Android][android].
  120. *
  121. * [ChromeDriver]: https://sites.google.com/a/chromium.org/chromedriver/
  122. * [ChromeDriver release]: http://chromedriver.storage.googleapis.com/index.html
  123. * [PATH]: http://en.wikipedia.org/wiki/PATH_%28variable%29
  124. * [android]: https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android
  125. * [webview]: https://developer.chrome.com/multidevice/webview/overview
  126. */
  127. 'use strict';
  128. const fs = require('fs');
  129. const util = require('util');
  130. const http = require('./http');
  131. const io = require('./io');
  132. const {Capabilities, Capability} = require('./lib/capabilities');
  133. const command = require('./lib/command');
  134. const logging = require('./lib/logging');
  135. const promise = require('./lib/promise');
  136. const Symbols = require('./lib/symbols');
  137. const webdriver = require('./lib/webdriver');
  138. const portprober = require('./net/portprober');
  139. const remote = require('./remote');
  140. /**
  141. * Name of the ChromeDriver executable.
  142. * @type {string}
  143. * @const
  144. */
  145. const CHROMEDRIVER_EXE =
  146. process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
  147. /**
  148. * Custom command names supported by ChromeDriver.
  149. * @enum {string}
  150. */
  151. const Command = {
  152. LAUNCH_APP: 'launchApp',
  153. GET_NETWORK_CONDITIONS: 'getNetworkConditions',
  154. SET_NETWORK_CONDITIONS: 'setNetworkConditions'
  155. };
  156. /**
  157. * Creates a command executor with support for ChromeDriver's custom commands.
  158. * @param {!Promise<string>} url The server's URL.
  159. * @return {!command.Executor} The new command executor.
  160. */
  161. function createExecutor(url) {
  162. let client = url.then(url => new http.HttpClient(url));
  163. let executor = new http.Executor(client);
  164. configureExecutor(executor);
  165. return executor;
  166. }
  167. /**
  168. * Configures the given executor with Chrome-specific commands.
  169. * @param {!http.Executor} executor the executor to configure.
  170. */
  171. function configureExecutor(executor) {
  172. executor.defineCommand(
  173. Command.LAUNCH_APP,
  174. 'POST',
  175. '/session/:sessionId/chromium/launch_app');
  176. executor.defineCommand(
  177. Command.GET_NETWORK_CONDITIONS,
  178. 'GET',
  179. '/session/:sessionId/chromium/network_conditions');
  180. executor.defineCommand(
  181. Command.SET_NETWORK_CONDITIONS,
  182. 'POST',
  183. '/session/:sessionId/chromium/network_conditions');
  184. }
  185. /**
  186. * Creates {@link selenium-webdriver/remote.DriverService} instances that manage
  187. * a [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/)
  188. * server in a child process.
  189. */
  190. class ServiceBuilder extends remote.DriverService.Builder {
  191. /**
  192. * @param {string=} opt_exe Path to the server executable to use. If omitted,
  193. * the builder will attempt to locate the chromedriver on the current
  194. * PATH.
  195. * @throws {Error} If provided executable does not exist, or the chromedriver
  196. * cannot be found on the PATH.
  197. */
  198. constructor(opt_exe) {
  199. let exe = opt_exe || io.findInPath(CHROMEDRIVER_EXE, true);
  200. if (!exe) {
  201. throw Error(
  202. 'The ChromeDriver could not be found on the current PATH. Please ' +
  203. 'download the latest version of the ChromeDriver from ' +
  204. 'http://chromedriver.storage.googleapis.com/index.html and ensure ' +
  205. 'it can be found on your PATH.');
  206. }
  207. super(exe);
  208. this.setLoopback(true); // Required
  209. }
  210. /**
  211. * Sets which port adb is listening to. _The ChromeDriver will connect to adb
  212. * if an {@linkplain Options#androidPackage Android session} is requested, but
  213. * adb **must** be started beforehand._
  214. *
  215. * @param {number} port Which port adb is running on.
  216. * @return {!ServiceBuilder} A self reference.
  217. */
  218. setAdbPort(port) {
  219. return this.addArguments('--adb-port=' + port);
  220. }
  221. /**
  222. * Sets the path of the log file the driver should log to. If a log file is
  223. * not specified, the driver will log to stderr.
  224. * @param {string} path Path of the log file to use.
  225. * @return {!ServiceBuilder} A self reference.
  226. */
  227. loggingTo(path) {
  228. return this.addArguments('--log-path=' + path);
  229. }
  230. /**
  231. * Enables verbose logging.
  232. * @return {!ServiceBuilder} A self reference.
  233. */
  234. enableVerboseLogging() {
  235. return this.addArguments('--verbose');
  236. }
  237. /**
  238. * Sets the number of threads the driver should use to manage HTTP requests.
  239. * By default, the driver will use 4 threads.
  240. * @param {number} n The number of threads to use.
  241. * @return {!ServiceBuilder} A self reference.
  242. */
  243. setNumHttpThreads(n) {
  244. return this.addArguments('--http-threads=' + n);
  245. }
  246. /**
  247. * @override
  248. */
  249. setPath(path) {
  250. super.setPath(path);
  251. return this.addArguments('--url-base=' + path);
  252. }
  253. }
  254. /** @type {remote.DriverService} */
  255. let defaultService = null;
  256. /**
  257. * Sets the default service to use for new ChromeDriver instances.
  258. * @param {!remote.DriverService} service The service to use.
  259. * @throws {Error} If the default service is currently running.
  260. */
  261. function setDefaultService(service) {
  262. if (defaultService && defaultService.isRunning()) {
  263. throw Error(
  264. 'The previously configured ChromeDriver service is still running. ' +
  265. 'You must shut it down before you may adjust its configuration.');
  266. }
  267. defaultService = service;
  268. }
  269. /**
  270. * Returns the default ChromeDriver service. If such a service has not been
  271. * configured, one will be constructed using the default configuration for
  272. * a ChromeDriver executable found on the system PATH.
  273. * @return {!remote.DriverService} The default ChromeDriver service.
  274. */
  275. function getDefaultService() {
  276. if (!defaultService) {
  277. defaultService = new ServiceBuilder().build();
  278. }
  279. return defaultService;
  280. }
  281. const OPTIONS_CAPABILITY_KEY = 'chromeOptions';
  282. /**
  283. * Class for managing ChromeDriver specific options.
  284. */
  285. class Options {
  286. constructor() {
  287. /** @private {!Object} */
  288. this.options_ = {};
  289. /** @private {!Array<(string|!Buffer)>} */
  290. this.extensions_ = [];
  291. /** @private {?logging.Preferences} */
  292. this.logPrefs_ = null;
  293. /** @private {?./lib/capabilities.ProxyConfig} */
  294. this.proxy_ = null;
  295. }
  296. /**
  297. * Extracts the ChromeDriver specific options from the given capabilities
  298. * object.
  299. * @param {!Capabilities} caps The capabilities object.
  300. * @return {!Options} The ChromeDriver options.
  301. */
  302. static fromCapabilities(caps) {
  303. let options = new Options();
  304. let o = caps.get(OPTIONS_CAPABILITY_KEY);
  305. if (o instanceof Options) {
  306. options = o;
  307. } else if (o) {
  308. options.
  309. addArguments(o.args || []).
  310. addExtensions(o.extensions || []).
  311. detachDriver(o.detach).
  312. excludeSwitches(o.excludeSwitches || []).
  313. setChromeBinaryPath(o.binary).
  314. setChromeLogFile(o.logPath).
  315. setChromeMinidumpPath(o.minidumpPath).
  316. setLocalState(o.localState).
  317. setMobileEmulation(o.mobileEmulation).
  318. setUserPreferences(o.prefs).
  319. setPerfLoggingPrefs(o.perfLoggingPrefs);
  320. }
  321. if (caps.has(Capability.PROXY)) {
  322. options.setProxy(caps.get(Capability.PROXY));
  323. }
  324. if (caps.has(Capability.LOGGING_PREFS)) {
  325. options.setLoggingPrefs(
  326. caps.get(Capability.LOGGING_PREFS));
  327. }
  328. return options;
  329. }
  330. /**
  331. * Add additional command line arguments to use when launching the Chrome
  332. * browser. Each argument may be specified with or without the "--" prefix
  333. * (e.g. "--foo" and "foo"). Arguments with an associated value should be
  334. * delimited by an "=": "foo=bar".
  335. *
  336. * @param {...(string|!Array<string>)} args The arguments to add.
  337. * @return {!Options} A self reference.
  338. */
  339. addArguments(...args) {
  340. let newArgs = (this.options_.args || []).concat(...args);
  341. if (newArgs.length) {
  342. this.options_.args = newArgs;
  343. }
  344. return this;
  345. }
  346. /**
  347. * Configures the chromedriver to start Chrome in headless mode.
  348. *
  349. * > __NOTE:__ Resizing the browser window in headless mode is only supported
  350. * > in Chrome 60. Users are encouraged to set an initial window size with
  351. * > the {@link #windowSize windowSize({width, height})} option.
  352. *
  353. * @return {!Options} A self reference.
  354. */
  355. headless() {
  356. // TODO(jleyba): Remove `disable-gpu` once head Chrome no longer requires
  357. // that to be set.
  358. return this.addArguments('headless', 'disable-gpu');
  359. }
  360. /**
  361. * Sets the initial window size.
  362. *
  363. * @param {{width: number, height: number}} size The desired window size.
  364. * @return {!Options} A self reference.
  365. * @throws {TypeError} if width or height is unspecified, not a number, or
  366. * less than or equal to 0.
  367. */
  368. windowSize({width, height}) {
  369. function checkArg(arg) {
  370. if (typeof arg !== 'number' || arg <= 0) {
  371. throw TypeError('Arguments must be {width, height} with numbers > 0');
  372. }
  373. }
  374. checkArg(width);
  375. checkArg(height);
  376. return this.addArguments(`window-size=${width},${height}`);
  377. }
  378. /**
  379. * List of Chrome command line switches to exclude that ChromeDriver by default
  380. * passes when starting Chrome. Do not prefix switches with "--".
  381. *
  382. * @param {...(string|!Array<string>)} args The switches to exclude.
  383. * @return {!Options} A self reference.
  384. */
  385. excludeSwitches(...args) {
  386. let switches = (this.options_.excludeSwitches || []).concat(...args);
  387. if (switches.length) {
  388. this.options_.excludeSwitches = switches;
  389. }
  390. return this;
  391. }
  392. /**
  393. * Add additional extensions to install when launching Chrome. Each extension
  394. * should be specified as the path to the packed CRX file, or a Buffer for an
  395. * extension.
  396. * @param {...(string|!Buffer|!Array<(string|!Buffer)>)} args The
  397. * extensions to add.
  398. * @return {!Options} A self reference.
  399. */
  400. addExtensions(...args) {
  401. this.extensions_ = this.extensions_.concat(...args);
  402. return this;
  403. }
  404. /**
  405. * Sets the path to the Chrome binary to use. On Mac OS X, this path should
  406. * reference the actual Chrome executable, not just the application binary
  407. * (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome").
  408. *
  409. * The binary path be absolute or relative to the chromedriver server
  410. * executable, but it must exist on the machine that will launch Chrome.
  411. *
  412. * @param {string} path The path to the Chrome binary to use.
  413. * @return {!Options} A self reference.
  414. */
  415. setChromeBinaryPath(path) {
  416. this.options_.binary = path;
  417. return this;
  418. }
  419. /**
  420. * Sets whether to leave the started Chrome browser running if the controlling
  421. * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is
  422. * called.
  423. * @param {boolean} detach Whether to leave the browser running if the
  424. * chromedriver service is killed before the session.
  425. * @return {!Options} A self reference.
  426. */
  427. detachDriver(detach) {
  428. this.options_.detach = detach;
  429. return this;
  430. }
  431. /**
  432. * Sets the user preferences for Chrome's user profile. See the "Preferences"
  433. * file in Chrome's user data directory for examples.
  434. * @param {!Object} prefs Dictionary of user preferences to use.
  435. * @return {!Options} A self reference.
  436. */
  437. setUserPreferences(prefs) {
  438. this.options_.prefs = prefs;
  439. return this;
  440. }
  441. /**
  442. * Sets the logging preferences for the new session.
  443. * @param {!logging.Preferences} prefs The logging preferences.
  444. * @return {!Options} A self reference.
  445. */
  446. setLoggingPrefs(prefs) {
  447. this.logPrefs_ = prefs;
  448. return this;
  449. }
  450. /**
  451. * Sets the performance logging preferences. Options include:
  452. *
  453. * - `enableNetwork`: Whether or not to collect events from Network domain.
  454. * - `enablePage`: Whether or not to collect events from Page domain.
  455. * - `enableTimeline`: Whether or not to collect events from Timeline domain.
  456. * Note: when tracing is enabled, Timeline domain is implicitly disabled,
  457. * unless `enableTimeline` is explicitly set to true.
  458. * - `tracingCategories`: A comma-separated string of Chrome tracing
  459. * categories for which trace events should be collected. An unspecified
  460. * or empty string disables tracing.
  461. * - `bufferUsageReportingInterval`: The requested number of milliseconds
  462. * between DevTools trace buffer usage events. For example, if 1000, then
  463. * once per second, DevTools will report how full the trace buffer is. If
  464. * a report indicates the buffer usage is 100%, a warning will be issued.
  465. *
  466. * @param {{enableNetwork: boolean,
  467. * enablePage: boolean,
  468. * enableTimeline: boolean,
  469. * tracingCategories: string,
  470. * bufferUsageReportingInterval: number}} prefs The performance
  471. * logging preferences.
  472. * @return {!Options} A self reference.
  473. */
  474. setPerfLoggingPrefs(prefs) {
  475. this.options_.perfLoggingPrefs = prefs;
  476. return this;
  477. }
  478. /**
  479. * Sets preferences for the "Local State" file in Chrome's user data
  480. * directory.
  481. * @param {!Object} state Dictionary of local state preferences.
  482. * @return {!Options} A self reference.
  483. */
  484. setLocalState(state) {
  485. this.options_.localState = state;
  486. return this;
  487. }
  488. /**
  489. * Sets the name of the activity hosting a Chrome-based Android WebView. This
  490. * option must be set to connect to an [Android WebView](
  491. * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android)
  492. *
  493. * @param {string} name The activity name.
  494. * @return {!Options} A self reference.
  495. */
  496. androidActivity(name) {
  497. this.options_.androidActivity = name;
  498. return this;
  499. }
  500. /**
  501. * Sets the device serial number to connect to via ADB. If not specified, the
  502. * ChromeDriver will select an unused device at random. An error will be
  503. * returned if all devices already have active sessions.
  504. *
  505. * @param {string} serial The device serial number to connect to.
  506. * @return {!Options} A self reference.
  507. */
  508. androidDeviceSerial(serial) {
  509. this.options_.androidDeviceSerial = serial;
  510. return this;
  511. }
  512. /**
  513. * Configures the ChromeDriver to launch Chrome on Android via adb. This
  514. * function is shorthand for
  515. * {@link #androidPackage options.androidPackage('com.android.chrome')}.
  516. * @return {!Options} A self reference.
  517. */
  518. androidChrome() {
  519. return this.androidPackage('com.android.chrome');
  520. }
  521. /**
  522. * Sets the package name of the Chrome or WebView app.
  523. *
  524. * @param {?string} pkg The package to connect to, or `null` to disable Android
  525. * and switch back to using desktop Chrome.
  526. * @return {!Options} A self reference.
  527. */
  528. androidPackage(pkg) {
  529. this.options_.androidPackage = pkg;
  530. return this;
  531. }
  532. /**
  533. * Sets the process name of the Activity hosting the WebView (as given by
  534. * `ps`). If not specified, the process name is assumed to be the same as
  535. * {@link #androidPackage}.
  536. *
  537. * @param {string} processName The main activity name.
  538. * @return {!Options} A self reference.
  539. */
  540. androidProcess(processName) {
  541. this.options_.androidProcess = processName;
  542. return this;
  543. }
  544. /**
  545. * Sets whether to connect to an already-running instead of the specified
  546. * {@linkplain #androidProcess app} instead of launching the app with a clean
  547. * data directory.
  548. *
  549. * @param {boolean} useRunning Whether to connect to a running instance.
  550. * @return {!Options} A self reference.
  551. */
  552. androidUseRunningApp(useRunning) {
  553. this.options_.androidUseRunningApp = useRunning;
  554. return this;
  555. }
  556. /**
  557. * Sets the path to Chrome's log file. This path should exist on the machine
  558. * that will launch Chrome.
  559. * @param {string} path Path to the log file to use.
  560. * @return {!Options} A self reference.
  561. */
  562. setChromeLogFile(path) {
  563. this.options_.logPath = path;
  564. return this;
  565. }
  566. /**
  567. * Sets the directory to store Chrome minidumps in. This option is only
  568. * supported when ChromeDriver is running on Linux.
  569. * @param {string} path The directory path.
  570. * @return {!Options} A self reference.
  571. */
  572. setChromeMinidumpPath(path) {
  573. this.options_.minidumpPath = path;
  574. return this;
  575. }
  576. /**
  577. * Configures Chrome to emulate a mobile device. For more information, refer
  578. * to the ChromeDriver project page on [mobile emulation][em]. Configuration
  579. * options include:
  580. *
  581. * - `deviceName`: The name of a pre-configured [emulated device][devem]
  582. * - `width`: screen width, in pixels
  583. * - `height`: screen height, in pixels
  584. * - `pixelRatio`: screen pixel ratio
  585. *
  586. * __Example 1: Using a Pre-configured Device__
  587. *
  588. * let options = new chrome.Options().setMobileEmulation(
  589. * {deviceName: 'Google Nexus 5'});
  590. *
  591. * let driver = chrome.Driver.createSession(options);
  592. *
  593. * __Example 2: Using Custom Screen Configuration__
  594. *
  595. * let options = new chrome.Options().setMobileEmulation({
  596. * width: 360,
  597. * height: 640,
  598. * pixelRatio: 3.0
  599. * });
  600. *
  601. * let driver = chrome.Driver.createSession(options);
  602. *
  603. *
  604. * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation
  605. * [devem]: https://developer.chrome.com/devtools/docs/device-mode
  606. *
  607. * @param {?({deviceName: string}|
  608. * {width: number, height: number, pixelRatio: number})} config The
  609. * mobile emulation configuration, or `null` to disable emulation.
  610. * @return {!Options} A self reference.
  611. */
  612. setMobileEmulation(config) {
  613. this.options_.mobileEmulation = config;
  614. return this;
  615. }
  616. /**
  617. * Sets the proxy settings for the new session.
  618. * @param {./lib/capabilities.ProxyConfig} proxy The proxy configuration to
  619. * use.
  620. * @return {!Options} A self reference.
  621. */
  622. setProxy(proxy) {
  623. this.proxy_ = proxy;
  624. return this;
  625. }
  626. /**
  627. * Converts this options instance to a {@link Capabilities} object.
  628. * @param {Capabilities=} opt_capabilities The capabilities to merge
  629. * these options into, if any.
  630. * @return {!Capabilities} The capabilities.
  631. */
  632. toCapabilities(opt_capabilities) {
  633. let caps = opt_capabilities || Capabilities.chrome();
  634. caps.
  635. set(Capability.PROXY, this.proxy_).
  636. set(Capability.LOGGING_PREFS, this.logPrefs_).
  637. set(OPTIONS_CAPABILITY_KEY, this);
  638. return caps;
  639. }
  640. /**
  641. * Converts this instance to its JSON wire protocol representation. Note this
  642. * function is an implementation not intended for general use.
  643. * @return {!Object} The JSON wire protocol representation of this instance.
  644. */
  645. [Symbols.serialize]() {
  646. let json = {};
  647. for (let key in this.options_) {
  648. if (this.options_[key] != null) {
  649. json[key] = this.options_[key];
  650. }
  651. }
  652. if (this.extensions_.length) {
  653. json.extensions = this.extensions_.map(function(extension) {
  654. if (Buffer.isBuffer(extension)) {
  655. return extension.toString('base64');
  656. }
  657. return io.read(/** @type {string} */(extension))
  658. .then(buffer => buffer.toString('base64'));
  659. });
  660. }
  661. return json;
  662. }
  663. }
  664. /**
  665. * Creates a new WebDriver client for Chrome.
  666. */
  667. class Driver extends webdriver.WebDriver {
  668. /**
  669. * Creates a new session with the ChromeDriver.
  670. *
  671. * @param {(Capabilities|Options)=} opt_config The configuration options.
  672. * @param {(remote.DriverService|http.Executor)=} opt_serviceExecutor Either
  673. * a DriverService to use for the remote end, or a preconfigured executor
  674. * for an externally managed endpoint. If neither is provided, the
  675. * {@linkplain ##getDefaultService default service} will be used by
  676. * default.
  677. * @param {promise.ControlFlow=} opt_flow The control flow to use, or `null`
  678. * to use the currently active flow.
  679. * @return {!Driver} A new driver instance.
  680. */
  681. static createSession(opt_config, opt_serviceExecutor, opt_flow) {
  682. let executor;
  683. if (opt_serviceExecutor instanceof http.Executor) {
  684. executor = opt_serviceExecutor;
  685. configureExecutor(executor);
  686. } else {
  687. let service = opt_serviceExecutor || getDefaultService();
  688. executor = createExecutor(service.start());
  689. }
  690. let caps =
  691. opt_config instanceof Options ? opt_config.toCapabilities() :
  692. (opt_config || Capabilities.chrome());
  693. return /** @type {!Driver} */(
  694. super.createSession(executor, caps, opt_flow));
  695. }
  696. /**
  697. * This function is a no-op as file detectors are not supported by this
  698. * implementation.
  699. * @override
  700. */
  701. setFileDetector() {}
  702. /**
  703. * Schedules a command to launch Chrome App with given ID.
  704. * @param {string} id ID of the App to launch.
  705. * @return {!promise.Thenable<void>} A promise that will be resolved
  706. * when app is launched.
  707. */
  708. launchApp(id) {
  709. return this.schedule(
  710. new command.Command(Command.LAUNCH_APP).setParameter('id', id),
  711. 'Driver.launchApp()');
  712. }
  713. /**
  714. * Schedules a command to get Chrome network emulation settings.
  715. * @return {!promise.Thenable<T>} A promise that will be resolved
  716. * when network emulation settings are retrievied.
  717. */
  718. getNetworkConditions() {
  719. return this.schedule(
  720. new command.Command(Command.GET_NETWORK_CONDITIONS),
  721. 'Driver.getNetworkConditions()');
  722. }
  723. /**
  724. * Schedules a command to set Chrome network emulation settings.
  725. *
  726. * __Sample Usage:__
  727. *
  728. * driver.setNetworkConditions({
  729. * offline: false,
  730. * latency: 5, // Additional latency (ms).
  731. * download_throughput: 500 * 1024, // Maximal aggregated download throughput.
  732. * upload_throughput: 500 * 1024 // Maximal aggregated upload throughput.
  733. * });
  734. *
  735. * @param {Object} spec Defines the network conditions to set
  736. * @return {!promise.Thenable<void>} A promise that will be resolved
  737. * when network emulation settings are set.
  738. */
  739. setNetworkConditions(spec) {
  740. if (!spec || typeof spec !== 'object') {
  741. throw TypeError('setNetworkConditions called with non-network-conditions parameter');
  742. }
  743. return this.schedule(
  744. new command.Command(Command.SET_NETWORK_CONDITIONS).setParameter('network_conditions', spec),
  745. 'Driver.setNetworkConditions(' + JSON.stringify(spec) + ')');
  746. }
  747. }
  748. // PUBLIC API
  749. exports.Driver = Driver;
  750. exports.Options = Options;
  751. exports.ServiceBuilder = ServiceBuilder;
  752. exports.getDefaultService = getDefaultService;
  753. exports.setDefaultService = setDefaultService;