download_manager.js 2.3 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. DownloadManager.prototype = {
  38. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  39. if (!pdfjsLib.createValidAbsoluteUrl(url, 'http://example.com')) {
  40. return;
  41. }
  42. download(url + '#pdfjs.action=download', filename);
  43. },
  44. downloadData: function DownloadManager_downloadData(data, filename, contentType) {
  45. if (navigator.msSaveBlob) {
  46. return navigator.msSaveBlob(new Blob([data], { type: contentType }), filename);
  47. }
  48. var blobUrl = pdfjsLib.createObjectURL(data, contentType, pdfjsLib.PDFJS.disableCreateObjectURL);
  49. download(blobUrl, filename);
  50. },
  51. download: function DownloadManager_download(blob, url, filename) {
  52. if (navigator.msSaveBlob) {
  53. if (!navigator.msSaveBlob(blob, filename)) {
  54. this.downloadUrl(url, filename);
  55. }
  56. return;
  57. }
  58. if (pdfjsLib.PDFJS.disableCreateObjectURL) {
  59. this.downloadUrl(url, filename);
  60. return;
  61. }
  62. var blobUrl = URL.createObjectURL(blob);
  63. download(blobUrl, filename);
  64. }
  65. };
  66. exports.DownloadManager = DownloadManager;