Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for downloading the chromedriver after installation #332

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ Another option is to use PATH variable `CHROMEDRIVER_FORCE_DOWNLOAD`.
CHROMEDRIVER_FORCE_DOWNLOAD=true npm install chromedriver
```

Additionally, you can force a chromedriver executable to be downloaded at runtime.

```js
await chromedriver.download();
```

The `download` function also supports taking an options dictionary that can be used
to specify `cdn_url` and/or `download_version` (which can be the full version of chrome
("84.0.4147.105") or just the major version ("84")).

```js
await chromedriver.download({cdn_url: "http://localhost", download_version: "84"});
```

## Custom binaries url

To use a mirror of the ChromeDriver binaries use npm config property `chromedriver_cdnurl`.
Expand Down
107 changes: 72 additions & 35 deletions install.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,42 +33,44 @@ let chromedriver_version = process.env.npm_config_chromedriver_version || proces
let chromedriverBinaryFilePath;
let downloadedFile = '';

(async function install() {
try {
if (detect_chromedriver_version === 'true') {
// Refer http://chromedriver.chromium.org/downloads/version-selection
const chromeVersion = await getChromeVersion();
console.log("Your Chrome version is " + chromeVersion);
const chromeVersionWithoutPatch = /^(.*?)\.\d+$/.exec(chromeVersion)[1];
await getChromeDriverVersion(getRequestOptions(cdnUrl + '/LATEST_RELEASE_' + chromeVersionWithoutPatch));
console.log("Compatible ChromeDriver version is " + chromedriver_version);
}
if (chromedriver_version === 'LATEST') {
await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE`));
} else {
const latestReleaseForVersionMatch = chromedriver_version.match(/LATEST_(\d+)/);
if (latestReleaseForVersionMatch) {
const majorVersion = latestReleaseForVersionMatch[1];
await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE_${majorVersion}`));
if (require.main === module) {
(async function install() {
try {
if (detect_chromedriver_version === 'true') {
niehusst marked this conversation as resolved.
Show resolved Hide resolved
// Refer http://chromedriver.chromium.org/downloads/version-selection
const chromeVersion = await getChromeVersion();
console.log("Your Chrome version is " + chromeVersion);
const chromeVersionWithoutPatch = /^(.*?)\.\d+$/.exec(chromeVersion)[1];
await getChromeDriverVersion(getRequestOptions(cdnUrl + '/LATEST_RELEASE_' + chromeVersionWithoutPatch));
console.log("Compatible ChromeDriver version is " + chromedriver_version);
}
if (chromedriver_version === 'LATEST') {
await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE`));
} else {
const latestReleaseForVersionMatch = chromedriver_version.match(/LATEST_(\d+)/);
if (latestReleaseForVersionMatch) {
const majorVersion = latestReleaseForVersionMatch[1];
await getChromeDriverVersion(getRequestOptions(`${cdnUrl}/LATEST_RELEASE_${majorVersion}`));
}
}
const tmpPath = findSuitableTempDirectory();
const chromedriverBinaryFileName = process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
chromedriverBinaryFilePath = path.resolve(tmpPath, chromedriverBinaryFileName);
const chromedriverIsAvailable = await verifyIfChromedriverIsAvailableAndHasCorrectVersion(chromedriver_version);
if (!chromedriverIsAvailable) {
console.log('Current existing ChromeDriver binary is unavailable, proceeding with download and extraction.');
await downloadFile(tmpPath);
await extractDownload(tmpPath);
}
await copyIntoPlace(tmpPath, libPath);
fixFilePermissions();
console.log('Done. ChromeDriver binary available at', helper.path);
} catch (err) {
console.error('ChromeDriver installation failed', err);
process.exit(1);
}
const tmpPath = findSuitableTempDirectory();
const chromedriverBinaryFileName = process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
chromedriverBinaryFilePath = path.resolve(tmpPath, chromedriverBinaryFileName);
const chromedriverIsAvailable = await verifyIfChromedriverIsAvailableAndHasCorrectVersion();
if (!chromedriverIsAvailable) {
console.log('Current existing ChromeDriver binary is unavailable, proceeding with download and extraction.');
await downloadFile(tmpPath);
await extractDownload(tmpPath);
}
await copyIntoPlace(tmpPath, libPath);
fixFilePermissions();
console.log('Done. ChromeDriver binary available at', helper.path);
} catch (err) {
console.error('ChromeDriver installation failed', err);
process.exit(1);
}
})();
})();
}

function validatePlatform() {
/** @type string */
Expand Down Expand Up @@ -110,7 +112,7 @@ async function downloadFile(dirToLoadTo) {
}
}

function verifyIfChromedriverIsAvailableAndHasCorrectVersion() {
function verifyIfChromedriverIsAvailableAndHasCorrectVersion(chromedriver_version) {
if (!fs.existsSync(chromedriverBinaryFilePath))
return Promise.resolve(false);
const forceDownload = process.env.npm_config_chromedriver_force_download === 'true' || process.env.CHROMEDRIVER_FORCE_DOWNLOAD === 'true';
Expand Down Expand Up @@ -238,6 +240,12 @@ async function getChromeDriverVersion(requestOptions) {
const response = await axios(requestOptions);
chromedriver_version = response.data.trim();
console.log(`Chromedriver version is ${chromedriver_version}.`);
return chromedriver_version;
}

async function getChromeDriverVersionFromUrl(downloadPath) {
const requestOptions = getRequestOptions(downloadPath);
return getChromeDriverVersion(requestOptions);
}

/**
Expand Down Expand Up @@ -339,3 +347,32 @@ function Deferred() {
}.bind(this));
Object.freeze(this);
}

async function downloadChromedriver(cdnUrl, chromedriver_version, dirToLoadTo) {
if (detect_chromedriver_version !== 'true' && configuredfilePath) {
downloadedFile = configuredfilePath;
console.log('Using file: ', downloadedFile);
return;
} else {
const fileName = `chromedriver_${platform}.zip`;
const tempDownloadedFile = path.resolve(dirToLoadTo, fileName);
downloadedFile = tempDownloadedFile;
const formattedDownloadUrl = `${cdnUrl}/${chromedriver_version}/${fileName}`;
console.log('Downloading from file: ', formattedDownloadUrl);
console.log('Saving to file:', downloadedFile);
await requestBinary(getRequestOptions(formattedDownloadUrl), downloadedFile);
}
}

exports = {
downloadChromedriver,
verifyIfChromedriverIsAvailableAndHasCorrectVersion,
findSuitableTempDirectory,
getRequestOptions,
getChromeDriverVersion,
getChromeDriverVersionFromUrl,
requestBinary,
extractDownload,
copyIntoPlace,
fixFilePermissions,
};
87 changes: 87 additions & 0 deletions lib/chromedriver.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
const fs = require('fs');
const path = require('path');
const tcpPortUsed = require('tcp-port-used');
const utils = require('../install');
const { getChromeVersion } = require('@testim/chrome-version');

// Default to Google's CDN
let cdnUrl = process.env.npm_config_chromedriver_cdnurl || process.env.CHROMEDRIVER_CDNURL || 'https://chromedriver.storage.googleapis.com';
// adapt http://chromedriver.storage.googleapis.com/
cdnUrl = cdnUrl.replace(/\/+$/, '');

const libPath = path.join(__dirname, 'chromedriver');

function getPortFromArgs(args) {
let port = 9515;
if (!args) {
Expand Down Expand Up @@ -45,3 +55,80 @@ exports.stop = function () {
exports.defaultInstance.kill();
}
};

/**
* Downloads chromedriver executable to calling device. Some custom options are supported.
*
* We can pass in download_version or cdn_url like such:
* await chromedriver.download({cdn_url: "http://localhost", download_version: "84"});
*
* download_version is able to be passed in as the full version of chrome ("84.0.4147.105") or just the major version ("84")
*/
exports.download = async function (options) {
if (!options) {
// this allows us to handle non-existent properties more easily
options = {}
}
// allow for a custom cdn url to be set
if (options.cdn_url) {
cdnUrl = options.cdn_url;
}
// adapt http://chromedriver.storage.googleapis.com/
cdnUrl = cdnUrl.replace(/\/+$/, '');
try {
// allow for a version to be picked, but default to current installed version
let chromeVersion;
if (!options.download_version) {
chromeVersion = await getChromeVersion();
console.log('Installed Chrome version is ' + chromeVersion);
} else {
chromeVersion = options.download_version;
console.log('Selected version is ' + chromeVersion);
}

let chromeVersionWithoutPatch;
// allow both full version and major version as input
if (chromeVersion.includes('.')) {
chromeVersionWithoutPatch = /^(.*?)\.\d+$/.exec(chromeVersion)[1];
} else {
chromeVersionWithoutPatch = chromeVersion;
}
chromedriver_version = await utils.getChromeDriverVersionFromUrl(`${cdnUrl}/LATEST_RELEASE_${chromeVersionWithoutPatch}`);
console.log('Compatible ChromeDriver version is ' + chromedriver_version);

let latestReleaseForVersionMatch = chromedriver_version.match(/LATEST_(\d+)/);
if (latestReleaseForVersionMatch) {
let majorVersion = latestReleaseForVersionMatch[1];
chromedriver_version = await utils.getChromeDriverVersionFromUrl(`${cdnUrl}/LATEST_RELEASE_${majorVersion}`);
}
let tmpPath = utils.findSuitableTempDirectory(chromedriver_version);
let chromedriverIsAvailable = await utils.verifyIfChromedriverIsAvailableAndHasCorrectVersion(chromedriver_version);
if (!chromedriverIsAvailable || options.force_download === 'true') {
console.log('Current existing ChromeDriver binary is unavailable, proceeding with download and extraction.');
await utils.downloadChromedriver(cdnUrl, chromedriver_version, tmpPath);
await utils.extractDownload(tmpPath);
}
await utils.copyIntoPlace(tmpPath, libPath);
utils.fixFilePermissions();
console.log('Done. ChromeDriver binary available at', exports.path);
} catch (err) {
console.error('ChromeDriver installation failed', err);
process.exit(1);
}
};

exports.is_proper_version_installed = async function () {
let chromeVersion = await getChromeVersion();
let chromeVersionWithoutPatch = /^(.*?)\.\d+$/.exec(chromeVersion)[1];

chromedriver_version = await utils.getChromeDriverVersionFromUrl(`${cdnUrl}/LATEST_RELEASE_${chromeVersionWithoutPatch}`);

let latestReleaseForVersionMatch = chromedriver_version.match(/LATEST_(\d+)/);
if (latestReleaseForVersionMatch) {
let majorVersion = latestReleaseForVersionMatch[1];
chromedriver_version = await utils.getChromeDriverVersionFromUrl(`${cdnUrl}/LATEST_RELEASE_${majorVersion}`);
}
let chromedriverIsAvailable = await utils.verifyIfChromedriverIsAvailableAndHasCorrectVersion(chromedriver_version);
return chromedriverIsAvailable;
}