/**
* @function dowloadLink
* @summary
* Download/save an external file.
*
* @param {Object} opts
* @param {String} opts.url URL
* @param {string} opts.mimeType ex. 'jpg', 'pdf'
* @param {string} opts.name default = "download"
*/
function downloadLink (opts) {
var url = opts.url
var type = opts.mimeType
var name = opts.name || 'download'
if (window.$b.isMobile() || !window.fetch || !url || !type) return fallbackClickout(url)
window.fetch(url, { mode: 'cors' })
.then(function (resp) {
return resp.ok ? resp.arrayBuffer() : Promise.reject(new Error())
})
.then(function (buffer) {
var blob = new Blob([buffer], { type: type })
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveBlob
if (window.navigator && window.navigator.msSaveBlob) {
return window.navigator.msSaveBlob(blob, name) || Promise.reject(new Error())
}
var blobUrl = URL.createObjectURL(blob)
var a = document.createElement('a')
a.href = blobUrl
a.download = name
document.body.appendChild(a)
a.click()
// For Firefox it is necessary to delay revoking the ObjectURL
setTimeout(function () {
window.URL.revokeObjectURL(blobUrl)
document.body.removeChild(a)
}, 100)
})
.catch(function () {
fallbackClickout(url)
})
}
function fallbackClickout (url) {
window.$b.emitClick({ url: url, context: 'Download' })
}
window.$b = window.$b || {}
window.$b.snippets = window.$b.snippets || {}
var snippets = window.$b.snippets
snippets.downloadLink = downloadLink
if (window.module) {
window.module.exports = downloadLink
}