Using base64 encoded images using HtmlService in Script applications

Does Google Apps Script support using base64-encoded images using the HTML service? I am trying to add images to an HTML page using base64 encoding, but they do not appear on the last page.

The HTML I'm trying to use is:

<img src="data:'+contentType+';base64,'+encoded+'"/> 

When I register the html content just before it is rendered by the HTML service, it looks like:

 <img src="data:image/png;base64,iVBORw0KGgoAAAANSUh.....(base64 string)/> 

This works fine in JSFiddle and in plain HTML, but images are not displayed in Script applications. When viewing the source code on the displayed page, image tags look like this:

 <img src="null"> 

Is there any other way to add base64 based images to the page? I can get images as blob, but I donโ€™t think there is a way to directly add blob to HTML content.

+6
source share
3 answers

Starting in December 2014 , Google Apps Script added an additional IFRAME sandbox mode that supports data URIs (since it does not use the Caja compiler). The downside is that IFRAME mode is not compatible with older browsers, but depending on your requirements, which might not be a problem.

All that is required is to call setSandboxMode() in your template, and your data URI should work as expected:

 var output = HtmlService.createHtmlOutput( '<img src="data:' + contentType + ';base64,' + encoded + '"/>' ); output.setSandboxMode(HtmlService.SandboxMode.IFRAME); 
+2
source

This is Issue 1558 for the Google Caja compiler - visit and run it to โ€œvoteโ€ and receive updates. Have you tried testing in the Caja Testbed ?

An alternative would be for the server function to retrieve a base64 encoded image through UrlFetch, decode it with base64Decode , then save the blob as an image file and place it from Google Drive . I expect it to be very slow, unfortunately.

+2
source

To get a base64 encoded string primarily from Google Drive files:

GS

 var response = UrlFetchApp.fetch('https://googledrive.com/host/fileId/name.png'); var blob = response.getBlob(); var bytes = blob.getBytes(); var base64String = Utilities.base64Encode(bytes); Logger.log(base64String); // now copy and paste into html 

HTML

 <img src="data:image/png;base64, <base64String>" alt="img name" /> 
+1
source

All Articles