From f6548e463f1a2af0b5dbae065ee7463f8dc2478f Mon Sep 17 00:00:00 2001 From: Rob Wu Date: Mon, 6 Feb 2017 00:56:13 +0100 Subject: [PATCH] Open PDF attachments in the viewer instead of download If users want to download, they can quickly click on the Download button in the newly opened viewer. The blobUrl logic for Firefox relies on `disableCreateObjectURL` is never false in Firefox. If the assumption is invalid, then PDF attachments at the attachment view will not correctly be displayed, because a data-URL will be generated and `?` is treated as part of the data:-URL. --- web/pdf_attachment_viewer.js | 43 ++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/web/pdf_attachment_viewer.js b/web/pdf_attachment_viewer.js index dbfda4b3d..4b3e16f28 100644 --- a/web/pdf_attachment_viewer.js +++ b/web/pdf_attachment_viewer.js @@ -86,6 +86,38 @@ var PDFAttachmentViewer = (function PDFAttachmentViewerClosure() { this._renderedCapability.resolve(); }, + /** + * @private + */ + _bindPdfLink: + function PDFAttachmentViewer_bindPdfLink(button, content, filename) { + var blobUrl; + button.onclick = function() { + if (!blobUrl) { + blobUrl = pdfjsLib.createObjectURL( + content, 'application/pdf', pdfjsLib.PDFJS.disableCreateObjectURL); + } + var viewerUrl; + if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) { + // The current URL is the viewer, let's use it and append the file. + viewerUrl = '?file=' + encodeURIComponent(blobUrl + '#' + filename); + } else if (PDFJSDev.test('CHROME')) { + // In the Chrome extension, the URL is rewritten using the history API + // in viewer.js, so an absolute URL must be generated. + // eslint-disable-next-line no-undef + viewerUrl = chrome.runtime.getURL('/content/web/viewer.html') + + '?file=' + encodeURIComponent(blobUrl + '#' + filename); + } else { + // Let Firefox's content handler catch the URL and display the PDF. + // In Firefox PDFJS.disableCreateObjectURL is always false, so + // blobUrl is always a blob:-URL and never a data:-URL. + viewerUrl = blobUrl + '?' + encodeURIComponent(filename); + } + window.open(viewerUrl); + return false; + }; + }, + /** * @private */ @@ -124,11 +156,18 @@ var PDFAttachmentViewer = (function PDFAttachmentViewerClosure() { for (var i = 0; i < attachmentsCount; i++) { var item = attachments[names[i]]; var filename = pdfjsLib.getFilenameFromUrl(item.filename); + filename = pdfjsLib.removeNullCharacters(filename); + var div = document.createElement('div'); div.className = 'attachmentsItem'; var button = document.createElement('button'); - this._bindLink(button, item.content, filename); - button.textContent = pdfjsLib.removeNullCharacters(filename); + button.textContent = filename; + if (/\.pdf$/i.test(filename)) { + this._bindPdfLink(button, item.content, filename); + } else { + this._bindLink(button, item.content, filename); + } + div.appendChild(button); this.container.appendChild(div); }