Last active
January 28, 2021 14:57
-
-
Save dmitry/830e656bb501c3f669377728f4ca1816 to your computer and use it in GitHub Desktop.
Download files in cypress <6.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path') | |
const { promisify } = require('util') | |
const CDP = require('chrome-remote-interface') | |
const debug = require('debug')('cypress:server:protocol') | |
const rimraf = promisify(require('rimraf')) | |
let port = 0 | |
let client = null | |
module.exports = (on, config) => { | |
const downloadPath = path.resolve(config.projectRoot, './downloads') | |
function ensureRdpPort (args) { | |
const existing = args.find((arg) => | |
arg.startsWith('--remote-debugging-port') | |
) | |
if (existing) { | |
return Number(existing.split('=')[1]) | |
} | |
const port = 40000 + Math.round(Math.random() * 25000) | |
args.push(`--remote-debugging-port=${port}`) | |
return port | |
} | |
async function resetCRI () { | |
if (client) { | |
debug('resetting CRI client') | |
await client.close() | |
client = null | |
} | |
} | |
async function cleanDownloads () { | |
debug(`cleaning up downloads at ${downloadPath}`) | |
await rimraf(downloadPath) | |
} | |
async function allowDownloads () { | |
await resetCRI() | |
await cleanDownloads() | |
debug(`enabling downloads at ${downloadPath}`) | |
client = client || (await CDP({ port })) | |
return client.send('Browser.setDownloadBehavior', { | |
behavior: 'allow', | |
downloadPath | |
}) | |
} | |
on('before:browser:launch', (browser, options) => { | |
if (browser.family === 'chromium') { | |
debug('browser launch args or options %o', options) | |
const args = Array.isArray(options) | |
? options | |
: options.args | |
port = ensureRdpPort(args) | |
debug('ensureRdpPort %d', port) | |
debug('Chrome arguments %o', args) | |
} | |
if (browser.family === 'firefox') { | |
options.preferences['browser.download.dir'] = downloadPath | |
options.preferences['browser.download.folderList'] = 2 | |
options.preferences['browser.helperApps.neverAsk.saveToDisk'] = 'application/pdf' | |
options.preferences['browser.helperApps.alwaysAsk.force'] = 'false' | |
return options | |
} | |
}) | |
return { | |
resetCRI, | |
allowDownloads, | |
cleanDownloads | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
on('task', require('./download')(on, config)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment