How to display data URI for PDF in Chrome App?

2019-04-13 05:11发布

问题:

I have a data URI generated from a JavaScript PDF library (jsPDF) that seems to be OK, because when I display it with console.log and paste it into a browser URL field, it works. However, I can't get it to display from within the Chrome App, either in a Chrome App window or an ordinary browser window. The URI starts like this:

var uri = "data:application/pdf;base64,JVBERi0xLjMK ...";

When I do this:

chrome.app.window.create(uri);

The window opens, but it is trying to load the URI:

chrome-extension://gapkhdeaendagkjpchhemfhbpfcjgmep/data:application/pdf;base64,JVBERi0xLjMK ...

and in the window there is the message "This webpage is not found".

When I do this:

window.open(uri);

or

window.open(chrome.runtime.getURL(uri));

absolutely nothing happens. No browser window or tab opens, and no message is written to the console.

Has anyone done this?

回答1:

chrome.app.window.create will only load a resource from the packaged app, so you can't escape the chrome-extension://gapkhdea.../ address space there.

window.open when called from a packaged app window will use the default system handler to open the URL. I don't know of any common system configurations which have a default handler registered for the data scheme, which is probably why nothing happens.

What you want, if your goal is to display arbitrary untrusted content within a packaged app, is the webview tag. You can embed a Webview element directly into an app window's contents. You can use a data URI for its src attribute, which can be assigned dynamically.

Depending on your Chrome version, you may encounter permissions issues when the Webview attempts to load the PDF viewer plugin, but I just tested this with some PDF data and got beautifully displayed PDF rendering inside of a packaged app.