查找InlineImage的googleusercontent.com URL

时间:2019-02-07 08:25:42

标签: google-apps-script google-docs

每当我在Google文档中上传图片(即InlineImage)时,它就会将其上传到CDN并引用googleusercontent.com URL。如果我在DocumentApp上使用Google Apps脚本,则可以获取InlineImage的实例。我知道我可以将其转换为base64,然后为该图像创建数据URL。但是,与其创建这个巨大的URL,不如仅使用现有的googleusercontent.com URL。

如何找到InlineImage的googleusercontent.com URL?

1 个答案:

答案 0 :(得分:1)

基本上,您需要执行以下操作:

  1. 在InlineImage上设置唯一的替代描述。
  2. Get the HTML of the entire document
  3. 使用正则表达式使用步骤1中的唯一替代说明查找<img标记。

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;
}

该脚本显然还有改进的余地(例如,不会使其崩溃),但这对于我的用例来说已经足够了。