Data, Maps, Usability, and Performance

Image Proxy with Google App Scripts

Last updated on May 6, 2015 in Development

google app script example

I have been a big fan of Google App Scripts. This service allows you to build powerful scripts that can be scheduled and integrated with Google (email, Google Docs, Excel) and external APIs. You write in JavaScript, within a browser based code editor right in Google Drive and the script can even be published as a web app. The quotas or limits are pretty good so you can quickly build something powerful for free.

Today, I will show how to create an Image Proxy with Google App Scripts which would allow you to grab images from other domains or go around the browser’s same-origin policy. Basically, the Google App Script is a server side proxy for your client side request. So, if you are exporting SVG as an image with images hosted on another domain or saving HTML5 Canvas with toDataURL() method, this could help you avoid tainted canvas and browser security errors. But, really, it’s just a simple example of a Google App Script published as a web app.

The concept is simple. I execute a script and pass to it an image url which the script will retrieve and convert to data in base64 encoding. It would be even easier to just proxy or return the binary image but the App Script Content Service class does not allow a binary content output. So, the script has to convert the binary image to text and pass that back in the response. Lets look at the code.

We have one function that grabs a url query parameter, makes a request to that url with a UrlFetchApp call, uses Utilities.base64Encode service to convert the binary image into text, and then returns that in the response with ContentService.createTextOutput method. Here is an example for this image:

This is the Image Url to DataURL Converter:

Of course, if the server hosting the image does have CORS, then you could pull and convert or access the image data without needing a server side proxy. But without CORS headers, such a request will fail with “blocked from loading by Cross-Origin Resource Sharing policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource” errors.

Here are more Google App Script examples.


10 Best Practices for Google Apps Script

Tags: , , , ,

Facebook Twitter Hacker News Reddit More...