Skip to content

Instantly share code, notes, and snippets.

@dmitry
Last active January 28, 2021 14:57
Show Gist options
  • Save dmitry/830e656bb501c3f669377728f4ca1816 to your computer and use it in GitHub Desktop.
Save dmitry/830e656bb501c3f669377728f4ca1816 to your computer and use it in GitHub Desktop.

Revisions

  1. dmitry revised this gist Jan 28, 2021. 2 changed files with 2 additions and 0 deletions.
    File renamed without changes.
    2 changes: 2 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@

    on('task', require('./download')(on, config))
  2. dmitry created this gist Jan 28, 2021.
    84 changes: 84 additions & 0 deletions cypress-download.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    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
    }
    }