在 Apps 脚本中使用带有 HtmlService 的 base64 编码图像 [英] Using base64-encoded images with HtmlService in Apps Script

查看:16
本文介绍了在 Apps 脚本中使用带有 HtmlService 的 base64 编码图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google Apps Script 是否支持在 HTML 服务中使用 base64 编码的图像?我正在尝试使用 base64 编码将图像添加到 HTML 页面,但它们没有显示在最终页面中.

Does Google Apps Script support the use of base64-encoded images with HTML service? I am trying to add images to an HTML page using base64 encoding, but they are not displaying in the final page.

我尝试使用的 HTML 是:

The HTML I am trying to use is:

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

当我在 HTML 服务呈现之前记录 html 内容时,它显示为:

When I log the html content just before it is rendered by HTML service this appears as:

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

这在 JSFiddle 和普通 HTML 中工作正常,但在 Apps Script 中,图像不显示.在渲染页面查看源码时,图片标签显示如下:

This works fine in JSFiddle and in normal HTML, but in Apps Script, the images do not display. When viewing the source code on the rendered page, the image tags appear as follows:

<img src="null">

还有其他方法可以将 base64 编码的图像添加到页面中吗?我可以将图像作为 blob 获取,但我认为没有办法将 blob 直接添加到 HTML 内容中.

Is there another way to add base64-encoded images to the page? I can get the images as a blob, but I don't think there is a way to directly add a blob to the HTML content.

推荐答案

截至 2014 年 12 月,Google Apps Script 添加了额外的 IFRAME 沙盒模式,支持数据 URI(因为它不使用 Caja 编译器).缺点是 IFRAME 模式与旧浏览器不兼容,但取决于您的要求,这可能不是问题.

As of December 2014, Google Apps Script has added an additional IFRAME sandbox mode, which 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 that may not be an issue.

所需要做的就是调用 setSandboxMode() 在您的模板上,并且您的数据 URI 应该按预期工作:

All that's required is to call setSandboxMode() on your template, and your data URIs should work as expected:

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

output.setSandboxMode(HtmlService.SandboxMode.IFRAME);

这篇关于在 Apps 脚本中使用带有 HtmlService 的 base64 编码图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆