George
George

Reputation: 532

How do I set download directory for Google Chrome using Selenium (NodeJS)?

I have a test in NodeJS that downloads a file from a website using Google Chrome on the cloud (BrowserStack). I am trying to download the file to a directory in my project. I understand I have to set this via Chrome Options but no answers posted here to seem work.

Could someone please share an example how this is done using NodeJS? Below is one example I have tried that doesn't work.

module.exports.createChromeDriver = async function () {
    if (parameters.runOnCloud === true) {

        await filesDirectory.createAppDirIfRequired(paths.tempDir, paths.downloadDirName);

        let capabilities = {
            'name' : parameters.report,
            'browserName' : 'Chrome',
            'browser_version' : '79.0',
            'os' : 'OS X',
            'os_version' : 'Mojave',
            'resolution' : '1920x1080',
            'browserstack.user' : credentials.browserstack.user,
            'browserstack.key' : credentials.browserstack.key,
            'browserstack.local' : 'true',
            'browserstack.localIdentifier': parameters.bsLocalIdentifier,
            'browserstack.networkLogs' : 'false',
        }

        if (parameters.tests === "wallet-web") {
            capabilities['browserstack.networkLogs'] = 'true';
        }

        let options = new chrome.Options();
        const prefs = {'download.default_directory' : paths.downloadsDir};
        options.addArguments('prefs', prefs);
        options.merge(capabilities);

        let driver = await new Builder().
            usingServer('http://hub-cloud.browserstack.com/wd/hub').
            withCapabilities(capabilities).
            build();

        return driver;
    }

Upvotes: 2

Views: 1402

Answers (1)

hoangdv
hoangdv

Reputation: 16157

You have a mistake when set the capabilities. capabilities does not include download option, because merge(options.merge(capabilities);) operator means , merge capabilities in to options.

You only need change one line:

withCapabilities(capabilities).

to

withCapabilities(options.toCapabilities()).

If it not working, I think you have to change the option variable, like:

const options = new chrome.Options();
options.setUserPreferences({
  'download.default_directory': paths.downloadsDir,
  'download.prompt_for_download': false, // Maybe
});
options.merge(capabilities);

Update:

The final way, you can try use

capabilities['goog:chromeOptions'] = options;

instead of

options.merge(capabilities);

Upvotes: 1

Related Questions