Skip to content

Instantly share code, notes, and snippets.

@dmitry

dmitry/download.js

Last active Jan 28, 2021
Embed
What would you like to do?
Download files in cypress <6.0
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
}
}
on('task', require('./download')(on, config))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment