0

Whenever I upload an image (i.e. InlineImage) in a Google Doc, it uploads it to a CDN and references a googleusercontent.com URL. If I'm using Google Apps Script on a DocumentApp, I can get an instance of InlineImage. I know I can convert it to a base64 and then create a data URL for this image. However, instead of creating this gigantic URL, I'd rather just use the existing googleusercontent.com URL.

How do I find out the googleusercontent.com URL for an InlineImage?

Senseful
  • 86,719
  • 67
  • 308
  • 465

1 Answers1

1

Essentially you need to do the following:

  1. Set a unique alt description on the InlineImage.
  2. Get the HTML of the entire document.
  3. Use a regex to find the <img tag using the unique alt description from step 1.

function getUrlOfInlineImage(inlineImage) {
  var altDescription = inlineImage.getAltDescription(); // warning: assumes that the alt description is a uuid. If it's not unique, this function might return a different image's url. If it's not a UUID, it might contain illegal regex characters and crash.
  if (!altDescription) {
    inlineImage.setAltDescription(Utilities.getUuid());
    // TODO: We currently crash because if we attempt to get the HTML right after calling setAltDescription(), it won't exist in the HTML. We must wait a bit of time before running it again. If there was something like DocumentApp.flush() (similar to how the Spreadsheet App has the same function), it might resolve this issue and we wouldn't need to crash.
    throw "Image was missing an alt description. Run again."
  }

  var html = getGoogleDocumentAsHTML();
  var regex = new RegExp('<img alt="' + altDescription + '" src="([^"]+)"');
  var matches = regex.exec(html);
  if (matches) {
    return matches[1];
  } else {
    return null;
  }
}

function getGoogleDocumentAsHTML() {
  var id = DocumentApp.getActiveDocument().getId() ;
  var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
  var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
  var param = {
    method      : "get",
    headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions:true,
  };
  var html = UrlFetchApp.fetch(url,param).getContentText();
  return html;
}

There is obviously room for improvement with the script (e.g. not making it crash), but this was good enough for my use-case.

Senseful
  • 86,719
  • 67
  • 308
  • 465