google-apps-script - cursorPos.insertInlineImage() 给出错误 : "We' re sorry, 发生服务器错误。请稍等一下,然后重试”

标签 google-apps-script

我正在尝试使用 Google 文档中包含的脚本从网址加载图像并将其插入到光标位置,但是使用 cursorPos.insertInlineImage(image) 插入图像会给出错误 很抱歉,服务器发生错误。请稍等一下,然后重试

使用 getBody().appendImage(image) 插入图像或使用 cursorPos.insertText("hello") 插入文本效果很好。

function onOpen(e) {
  var ui = DocumentApp.getUi();
  ui.createMenu("Test")
    .addItem("Insert", "insertTest")
    .addToUi();
}

function insertTest() {
  var doc = DocumentApp.getActiveDocument();
  var image = UrlFetchApp.fetch("http://latex.codecogs.com/gif.latex?E%3Dmc%5E2").getBlob();
  var cursorPos = doc.getCursor();
  doc.getBody().appendImage(image); // works
  cursorPos.insertText("test!"); // works
  cursorPos.insertInlineImage(image); // gives error
}

最佳答案

我很高兴地说找到了一个简单的解决方法!

function insertTest() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var image = UrlFetchApp.fetch("http://latex.codecogs.com/gif.latex?E%3Dmc%5E2").getBlob();
  var cursorElement = doc.getCursor().getElement();
  body.insertImage(body.getChildIndex(cursorElement), image);
}

不幸的是,如果光标位于段落内,这将抛出一个错误,指出cursorElement不是body的子元素。解决方案是将cursorElement 的最上层父级传递给getChildIndex。

function insertTest() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var image = UrlFetchApp.fetch("http://latex.codecogs.com/gif.latex?E%3Dmc%5E2").getBlob();
  var cursorElement = doc.getCursor().getElement();
  body.insertImage(body.getChildIndex(getTopLevelParent(cursorElement)), image);
}

// get the uppermost level parent of an element within a body section
function getTopLevelParent(element) {
  var parent = element.getParent();
  if (parent.getType() == DocumentApp.ElementType.BODY_SECTION) {
    return element;
  } else {
    return getTopLevelParent(parent);
  }
}

关于google-apps-script - cursorPos.insertInlineImage() 给出错误 : "We' re sorry, 发生服务器错误。请稍等一下,然后重试”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277368/

相关文章:

html - Apps 脚本 - 在 HtmlService 中使用来自 Google 云端硬盘的图像

google-apps-script - 修改某些电子表格时实时更新html内容

google-apps-script - 对于基于 UiApp 的 Web 应用程序,是否有任何好的示例或教程?

javascript - 找不到填充对象的函数 - 在控制台中有效,但不能作为宏

javascript - 在 Google Apps Script Web App 中使用 Google Visualization API 显示 GSheet 范围时出错

javascript - 在 Google Apps 脚本中,如果满足条件,如何仅发送一次电子邮件

mysql - 支持 Apps Script Web App 5000 个并发用户

javascript - jQuery UI效果 "shake"使div消失

ssl - 如何使用 SSL 将 Google Apps Script JDBC 连接到 Amazon RDS

google-apps-script - 使用通过 ScriptApp.getAuthToken() 获取的 AuthToken 调用 GAS 中的 Web 应用程序