download.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. function openUrl (url: string) {
  7. const opened = window.open(url, '_blank')
  8. if (!opened) {
  9. window.location.href = url
  10. }
  11. }
  12. export function download (data: Blob|string, downloadName = 'download') {
  13. // using ideas from https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js
  14. if (!data) return
  15. const ua = window.navigator.userAgent
  16. const isSafari = /Safari/i.test(ua)
  17. const isChromeIos = /CriOS\/[\d]+/.test(ua)
  18. const a = document.createElement('a')
  19. function open (str: string) {
  20. openUrl(isChromeIos ? str : str.replace(/^data:[^;]*;/, 'data:attachment/file;'))
  21. }
  22. if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {
  23. // native saveAs in IE 10+
  24. navigator.msSaveOrOpenBlob(data, downloadName)
  25. } else if ((isSafari || isChromeIos) && FileReader) {
  26. if (data instanceof Blob) {
  27. // no downloading of blob urls in Safari
  28. const reader = new FileReader()
  29. reader.onloadend = () => open(reader.result as string)
  30. reader.readAsDataURL(data)
  31. } else {
  32. open(data)
  33. }
  34. } else {
  35. let objectUrlCreated = false
  36. if (data instanceof Blob) {
  37. data = URL.createObjectURL(data)
  38. objectUrlCreated = true
  39. }
  40. if ('download' in a) {
  41. // download link available
  42. a.style.display = 'hidden'
  43. document.body.appendChild(a)
  44. a.href = data
  45. a.download = downloadName
  46. a.target = '_blank'
  47. a.click()
  48. document.body.removeChild(a)
  49. } else {
  50. openUrl(data)
  51. }
  52. if (objectUrlCreated) {
  53. window.URL.revokeObjectURL(data)
  54. }
  55. }
  56. }