2
0

download_manager.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. var pdfjsLib = require('./pdfjs.js');
  17. function download(blobUrl, filename) {
  18. var a = document.createElement('a');
  19. if (a.click) {
  20. a.href = blobUrl;
  21. a.target = '_parent';
  22. if ('download' in a) {
  23. a.download = filename;
  24. }
  25. (document.body || document.documentElement).appendChild(a);
  26. a.click();
  27. a.parentNode.removeChild(a);
  28. } else {
  29. if (window.top === window && blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  30. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  31. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  32. }
  33. window.open(blobUrl, '_parent');
  34. }
  35. }
  36. function DownloadManager() {
  37. }
  38. DownloadManager.prototype = {
  39. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  40. if (!pdfjsLib.createValidAbsoluteUrl(url, 'http://example.com')) {
  41. return;
  42. }
  43. download(url + '#pdfjs.action=download', filename);
  44. },
  45. downloadData: function DownloadManager_downloadData(data, filename, contentType) {
  46. if (navigator.msSaveBlob) {
  47. return navigator.msSaveBlob(new Blob([data], { type: contentType }), filename);
  48. }
  49. var blobUrl = pdfjsLib.createObjectURL(data, contentType, pdfjsLib.PDFJS.disableCreateObjectURL);
  50. download(blobUrl, filename);
  51. },
  52. download: function DownloadManager_download(blob, url, filename) {
  53. if (navigator.msSaveBlob) {
  54. if (!navigator.msSaveBlob(blob, filename)) {
  55. this.downloadUrl(url, filename);
  56. }
  57. return;
  58. }
  59. if (pdfjsLib.PDFJS.disableCreateObjectURL) {
  60. this.downloadUrl(url, filename);
  61. return;
  62. }
  63. var blobUrl = URL.createObjectURL(blob);
  64. download(blobUrl, filename);
  65. }
  66. };
  67. exports.DownloadManager = DownloadManager;