chrome.js

1// Copyright 2013 Selenium committers
2// Copyright 2013 Software Freedom Conservancy
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16/**
17 * @fileoverview Defines a {@linkplain Driver WebDriver} client for the
18 * [Chrome](https://sites.google.com/a/chromium.org/chromedriver/) web browser.
19 * Before using this module, you must download the latest
20 * [ChromeDriver release](http://chromedriver.storage.googleapis.com/index.html)
21 * and ensure it can be found on your system
22 * [PATH](http://en.wikipedia.org/wiki/PATH_%28variable%29).
23 *
24 * There are three primary classes exported by this module:
25 *
26 * 1. {@linkplain ServiceBuilder}: configures the
27 * {@link selenium-webdriver/remote.DriverService remote.DriverService}
28 * that manages the
29 * [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/)
30 * child process.
31 *
32 * 2. {@linkplain Options}: defines configuration options for each new Chrome
33 * session, such as which {@linkplain Options#setProxy proxy} to use,
34 * what {@linkplain Options#addExtensions extensions} to install, or
35 * what {@linkplain Options#addArguments command-line switches} to use when
36 * starting the browser.
37 *
38 * 3. {@linkplain Driver}: the WebDriver client; each new instance will control
39 * a unique browser session with a clean user profile (unless otherwise
40 * configured through the {@link Options} class).
41 *
42 *
43 * By default, every Chrome session will use a single driver service, which is
44 * started the first time a {@link Driver} instance is created and terminated
45 * when this process exits. The default service will inherit its environment
46 * from the current process and direct all output to /dev/null. You may obtain
47 * a handle to this default service using
48 * {@link #getDefaultService getDefaultService()} and change its configuration
49 * with {@link #setDefaultService setDefaultService()}.
50 *
51 * You may also create a {@link Driver} with its own driver service. This is
52 * useful if you need to capture the server's log output for a specific session:
53 *
54 * var chrome = require('selenium-webdriver/chrome');
55 *
56 * var service = new chrome.ServiceBuilder()
57 * .loggingTo('/my/log/file.txt')
58 * .enableVerboseLogging()
59 * .build();
60 *
61 * var options = new chrome.Options();
62 * // configure browser options ...
63 *
64 * var driver = new chrome.Driver(options, service);
65 *
66 * Users should only instantiate the {@link Driver} class directly when they
67 * need a custom driver service configuration (as shown above). For normal
68 * operation, users should start Chrome using the
69 * {@link selenium-webdriver.Builder}.
70 */
71
72'use strict';
73
74var fs = require('fs'),
75 util = require('util');
76
77var webdriver = require('./index'),
78 executors = require('./executors'),
79 io = require('./io'),
80 portprober = require('./net/portprober'),
81 remote = require('./remote');
82
83
84/**
85 * Name of the ChromeDriver executable.
86 * @type {string}
87 * @const
88 */
89var CHROMEDRIVER_EXE =
90 process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
91
92
93/**
94 * Creates {@link remote.DriverService} instances that manage a
95 * [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/)
96 * server in a child process.
97 *
98 * @param {string=} opt_exe Path to the server executable to use. If omitted,
99 * the builder will attempt to locate the chromedriver on the current
100 * PATH.
101 * @throws {Error} If provided executable does not exist, or the chromedriver
102 * cannot be found on the PATH.
103 * @constructor
104 */
105var ServiceBuilder = function(opt_exe) {
106 /** @private {string} */
107 this.exe_ = opt_exe || io.findInPath(CHROMEDRIVER_EXE, true);
108 if (!this.exe_) {
109 throw Error(
110 'The ChromeDriver could not be found on the current PATH. Please ' +
111 'download the latest version of the ChromeDriver from ' +
112 'http://chromedriver.storage.googleapis.com/index.html and ensure ' +
113 'it can be found on your PATH.');
114 }
115
116 if (!fs.existsSync(this.exe_)) {
117 throw Error('File does not exist: ' + this.exe_);
118 }
119
120 /** @private {!Array.<string>} */
121 this.args_ = [];
122 this.stdio_ = 'ignore';
123};
124
125
126/** @private {number} */
127ServiceBuilder.prototype.port_ = 0;
128
129
130/** @private {(string|!Array.<string|number|!Stream|null|undefined>)} */
131ServiceBuilder.prototype.stdio_ = 'ignore';
132
133
134/** @private {Object.<string, string>} */
135ServiceBuilder.prototype.env_ = null;
136
137
138/**
139 * Sets the port to start the ChromeDriver on.
140 * @param {number} port The port to use, or 0 for any free port.
141 * @return {!ServiceBuilder} A self reference.
142 * @throws {Error} If the port is invalid.
143 */
144ServiceBuilder.prototype.usingPort = function(port) {
145 if (port < 0) {
146 throw Error('port must be >= 0: ' + port);
147 }
148 this.port_ = port;
149 return this;
150};
151
152
153/**
154 * Sets the path of the log file the driver should log to. If a log file is
155 * not specified, the driver will log to stderr.
156 * @param {string} path Path of the log file to use.
157 * @return {!ServiceBuilder} A self reference.
158 */
159ServiceBuilder.prototype.loggingTo = function(path) {
160 this.args_.push('--log-path=' + path);
161 return this;
162};
163
164
165/**
166 * Enables verbose logging.
167 * @return {!ServiceBuilder} A self reference.
168 */
169ServiceBuilder.prototype.enableVerboseLogging = function() {
170 this.args_.push('--verbose');
171 return this;
172};
173
174
175/**
176 * Sets the number of threads the driver should use to manage HTTP requests.
177 * By default, the driver will use 4 threads.
178 * @param {number} n The number of threads to use.
179 * @return {!ServiceBuilder} A self reference.
180 */
181ServiceBuilder.prototype.setNumHttpThreads = function(n) {
182 this.args_.push('--http-threads=' + n);
183 return this;
184};
185
186
187/**
188 * Sets the base path for WebDriver REST commands (e.g. "/wd/hub").
189 * By default, the driver will accept commands relative to "/".
190 * @param {string} path The base path to use.
191 * @return {!ServiceBuilder} A self reference.
192 */
193ServiceBuilder.prototype.setUrlBasePath = function(path) {
194 this.args_.push('--url-base=' + path);
195 return this;
196};
197
198
199/**
200 * Defines the stdio configuration for the driver service. See
201 * {@code child_process.spawn} for more information.
202 * @param {(string|!Array.<string|number|!Stream|null|undefined>)} config The
203 * configuration to use.
204 * @return {!ServiceBuilder} A self reference.
205 */
206ServiceBuilder.prototype.setStdio = function(config) {
207 this.stdio_ = config;
208 return this;
209};
210
211
212/**
213 * Defines the environment to start the server under. This settings will be
214 * inherited by every browser session started by the server.
215 * @param {!Object.<string, string>} env The environment to use.
216 * @return {!ServiceBuilder} A self reference.
217 */
218ServiceBuilder.prototype.withEnvironment = function(env) {
219 this.env_ = env;
220 return this;
221};
222
223
224/**
225 * Creates a new DriverService using this instance's current configuration.
226 * @return {remote.DriverService} A new driver service using this instance's
227 * current configuration.
228 * @throws {Error} If the driver exectuable was not specified and a default
229 * could not be found on the current PATH.
230 */
231ServiceBuilder.prototype.build = function() {
232 var port = this.port_ || portprober.findFreePort();
233 var args = this.args_.concat(); // Defensive copy.
234
235 return new remote.DriverService(this.exe_, {
236 loopback: true,
237 port: port,
238 args: webdriver.promise.when(port, function(port) {
239 return args.concat('--port=' + port);
240 }),
241 env: this.env_,
242 stdio: this.stdio_
243 });
244};
245
246
247/** @type {remote.DriverService} */
248var defaultService = null;
249
250
251/**
252 * Sets the default service to use for new ChromeDriver instances.
253 * @param {!remote.DriverService} service The service to use.
254 * @throws {Error} If the default service is currently running.
255 */
256function setDefaultService(service) {
257 if (defaultService && defaultService.isRunning()) {
258 throw Error(
259 'The previously configured ChromeDriver service is still running. ' +
260 'You must shut it down before you may adjust its configuration.');
261 }
262 defaultService = service;
263}
264
265
266/**
267 * Returns the default ChromeDriver service. If such a service has not been
268 * configured, one will be constructed using the default configuration for
269 * a ChromeDriver executable found on the system PATH.
270 * @return {!remote.DriverService} The default ChromeDriver service.
271 */
272function getDefaultService() {
273 if (!defaultService) {
274 defaultService = new ServiceBuilder().build();
275 }
276 return defaultService;
277}
278
279
280/**
281 * @type {string}
282 * @const
283 */
284var OPTIONS_CAPABILITY_KEY = 'chromeOptions';
285
286
287/**
288 * Class for managing ChromeDriver specific options.
289 * @constructor
290 * @extends {webdriver.Serializable}
291 */
292var Options = function() {
293 webdriver.Serializable.call(this);
294
295 /** @private {!Array.<string>} */
296 this.args_ = [];
297
298 /** @private {!Array.<(string|!Buffer)>} */
299 this.extensions_ = [];
300};
301util.inherits(Options, webdriver.Serializable);
302
303
304/**
305 * Extracts the ChromeDriver specific options from the given capabilities
306 * object.
307 * @param {!webdriver.Capabilities} capabilities The capabilities object.
308 * @return {!Options} The ChromeDriver options.
309 */
310Options.fromCapabilities = function(capabilities) {
311 var options = new Options();
312
313 var o = capabilities.get(OPTIONS_CAPABILITY_KEY);
314 if (o instanceof Options) {
315 options = o;
316 } else if (o) {
317 options.
318 addArguments(o.args || []).
319 addExtensions(o.extensions || []).
320 detachDriver(!!o.detach).
321 setChromeBinaryPath(o.binary).
322 setChromeLogFile(o.logPath).
323 setLocalState(o.localState).
324 setUserPreferences(o.prefs);
325 }
326
327 if (capabilities.has(webdriver.Capability.PROXY)) {
328 options.setProxy(capabilities.get(webdriver.Capability.PROXY));
329 }
330
331 if (capabilities.has(webdriver.Capability.LOGGING_PREFS)) {
332 options.setLoggingPrefs(
333 capabilities.get(webdriver.Capability.LOGGING_PREFS));
334 }
335
336 return options;
337};
338
339
340/**
341 * Add additional command line arguments to use when launching the Chrome
342 * browser. Each argument may be specified with or without the "--" prefix
343 * (e.g. "--foo" and "foo"). Arguments with an associated value should be
344 * delimited by an "=": "foo=bar".
345 * @param {...(string|!Array.<string>)} var_args The arguments to add.
346 * @return {!Options} A self reference.
347 */
348Options.prototype.addArguments = function(var_args) {
349 this.args_ = this.args_.concat.apply(this.args_, arguments);
350 return this;
351};
352
353
354/**
355 * Add additional extensions to install when launching Chrome. Each extension
356 * should be specified as the path to the packed CRX file, or a Buffer for an
357 * extension.
358 * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The
359 * extensions to add.
360 * @return {!Options} A self reference.
361 */
362Options.prototype.addExtensions = function(var_args) {
363 this.extensions_ = this.extensions_.concat.apply(
364 this.extensions_, arguments);
365 return this;
366};
367
368
369/**
370 * Sets the path to the Chrome binary to use. On Mac OS X, this path should
371 * reference the actual Chrome executable, not just the application binary
372 * (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome").
373 *
374 * The binary path be absolute or relative to the chromedriver server
375 * executable, but it must exist on the machine that will launch Chrome.
376 *
377 * @param {string} path The path to the Chrome binary to use.
378 * @return {!Options} A self reference.
379 */
380Options.prototype.setChromeBinaryPath = function(path) {
381 this.binary_ = path;
382 return this;
383};
384
385
386/**
387 * Sets whether to leave the started Chrome browser running if the controlling
388 * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is
389 * called.
390 * @param {boolean} detach Whether to leave the browser running if the
391 * chromedriver service is killed before the session.
392 * @return {!Options} A self reference.
393 */
394Options.prototype.detachDriver = function(detach) {
395 this.detach_ = detach;
396 return this;
397};
398
399
400/**
401 * Sets the user preferences for Chrome's user profile. See the "Preferences"
402 * file in Chrome's user data directory for examples.
403 * @param {!Object} prefs Dictionary of user preferences to use.
404 * @return {!Options} A self reference.
405 */
406Options.prototype.setUserPreferences = function(prefs) {
407 this.prefs_ = prefs;
408 return this;
409};
410
411
412/**
413 * Sets the logging preferences for the new session.
414 * @param {!webdriver.logging.Preferences} prefs The logging preferences.
415 * @return {!Options} A self reference.
416 */
417Options.prototype.setLoggingPrefs = function(prefs) {
418 this.logPrefs_ = prefs;
419 return this;
420};
421
422
423/**
424 * Sets preferences for the "Local State" file in Chrome's user data
425 * directory.
426 * @param {!Object} state Dictionary of local state preferences.
427 * @return {!Options} A self reference.
428 */
429Options.prototype.setLocalState = function(state) {
430 this.localState_ = state;
431 return this;
432};
433
434
435/**
436 * Sets the path to Chrome's log file. This path should exist on the machine
437 * that will launch Chrome.
438 * @param {string} path Path to the log file to use.
439 * @return {!Options} A self reference.
440 */
441Options.prototype.setChromeLogFile = function(path) {
442 this.logFile_ = path;
443 return this;
444};
445
446
447/**
448 * Sets the proxy settings for the new session.
449 * @param {webdriver.ProxyConfig} proxy The proxy configuration to use.
450 * @return {!Options} A self reference.
451 */
452Options.prototype.setProxy = function(proxy) {
453 this.proxy_ = proxy;
454 return this;
455};
456
457
458/**
459 * Converts this options instance to a {@link webdriver.Capabilities} object.
460 * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge
461 * these options into, if any.
462 * @return {!webdriver.Capabilities} The capabilities.
463 */
464Options.prototype.toCapabilities = function(opt_capabilities) {
465 var capabilities = opt_capabilities || webdriver.Capabilities.chrome();
466 capabilities.
467 set(webdriver.Capability.PROXY, this.proxy_).
468 set(webdriver.Capability.LOGGING_PREFS, this.logPrefs_).
469 set(OPTIONS_CAPABILITY_KEY, this);
470 return capabilities;
471};
472
473
474/**
475 * Converts this instance to its JSON wire protocol representation. Note this
476 * function is an implementation not intended for general use.
477 * @return {{args: !Array.<string>,
478 * binary: (string|undefined),
479 * detach: boolean,
480 * extensions: !Array.<(string|!webdriver.promise.Promise.<string>)>,
481 * localState: (Object|undefined),
482 * logPath: (string|undefined),
483 * prefs: (Object|undefined)}} The JSON wire protocol representation
484 * of this instance.
485 * @override
486 */
487Options.prototype.serialize = function() {
488 var json = {
489 args: this.args_,
490 detach: !!this.detach_,
491 extensions: this.extensions_.map(function(extension) {
492 if (Buffer.isBuffer(extension)) {
493 return extension.toString('base64');
494 }
495 return webdriver.promise.checkedNodeCall(
496 fs.readFile, extension, 'base64');
497 })
498 };
499
500 // ChromeDriver barfs on null keys, so we must ensure these are not included
501 // if unset (really?)
502 if (this.binary_) {
503 json.binary = this.binary_;
504 }
505 if (this.localState_) {
506 json.localState = this.localState_;
507 }
508 if (this.logFile_) {
509 json.logPath = this.logFile_;
510 }
511 if (this.prefs_) {
512 json.prefs = this.prefs_;
513 }
514
515 return json;
516};
517
518
519/**
520 * Creates a new ChromeDriver session.
521 * @param {(webdriver.Capabilities|Options)=} opt_options The session options.
522 * @param {remote.DriverService=} opt_service The session to use; will use
523 * the {@link getDefaultService default service} by default.
524 * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or
525 * {@code null} to use the currently active flow.
526 * @return {!webdriver.WebDriver} A new WebDriver instance.
527 * @deprecated Use {@link Driver new Driver()}.
528 */
529function createDriver(opt_options, opt_service, opt_flow) {
530 return new Driver(opt_options, opt_service, opt_flow);
531}
532
533
534/**
535 * Creates a new WebDriver client for Chrome.
536 *
537 * @param {(webdriver.Capabilities|Options)=} opt_config The configuration
538 * options.
539 * @param {remote.DriverService=} opt_service The session to use; will use
540 * the {@link getDefaultService default service} by default.
541 * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or
542 * {@code null} to use the currently active flow.
543 * @constructor
544 * @extends {webdriver.WebDriver}
545 */
546var Driver = function(opt_config, opt_service, opt_flow) {
547 var service = opt_service || getDefaultService();
548 var executor = executors.createExecutor(service.start());
549
550 var capabilities =
551 opt_config instanceof Options ? opt_config.toCapabilities() :
552 (opt_config || webdriver.Capabilities.chrome());
553
554 var driver = webdriver.WebDriver.createSession(
555 executor, capabilities, opt_flow);
556
557 webdriver.WebDriver.call(
558 this, driver.getSession(), executor, driver.controlFlow());
559};
560util.inherits(Driver, webdriver.WebDriver);
561
562
563/**
564 * This function is a no-op as file detectors are not supported by this
565 * implementation.
566 * @override
567 */
568Driver.prototype.setFileDetector = function() {
569};
570
571
572// PUBLIC API
573
574
575exports.Driver = Driver;
576exports.Options = Options;
577exports.ServiceBuilder = ServiceBuilder;
578exports.createDriver = createDriver;
579exports.getDefaultService = getDefaultService;
580exports.setDefaultService = setDefaultService;