google 用于将进度条添加到 google 幻灯片的应用脚本

google app script to add progressbar to google slides

this link in developers.google.com 给出了一个 google 应用程序脚本,用于将进度条添加到 google 幻灯片。但是我无法让它工作......是代码不再工作了吗?或者除了那里给出的说明之外还有其他事情要做?这里的代码:

var BAR_ID = 'PROGRESS_BAR_ID';
var BAR_HEIGHT = 10; // px
var presentation = SlidesApp.getActivePresentation();

function onInstall(e) {
  onOpen();
}

function onOpen(e) {
  SlidesApp.getUi().createAddonMenu()
      .addItem('Show progress bar', 'createBars')
      .addItem('Hide progress bar', 'deleteBars')
      .addToUi();
}

//Create a rectangle on every slide with different bar widths.
function createBars() {
  deleteBars(); // Delete any existing progress bars
  var slides = presentation.getSlides();
  for (var i = 0; i < slides.length; ++i) {
    var ratioComplete = (i / (slides.length - 1));
    var x = 0;
    var y = presentation.getPageHeight() - BAR_HEIGHT;
    var barWidth = presentation.getPageWidth() * ratioComplete;
    if (barWidth > 0) {
      var bar = slides[i].insertShape(SlidesApp.ShapeType.RECTANGLE, x, y,
                                      barWidth, BAR_HEIGHT);
      bar.getBorder().setTransparent();
      bar.setLinkUrl(BAR_ID);
    }
  }
}

// Deletes all progress bar rectangles.
function deleteBars() {
  var slides = presentation.getSlides();
  for (var i = 0; i < slides.length; ++i) {
    var elements = slides[i].getPageElements();
    for (var j = 0; j < elements.length; ++j) {
      var el = elements[j];
      if (el.getPageElementType() === SlidesApp.PageElementType.SHAPE &&
          el.asShape().getLink() &&
          el.asShape().getLink().getUrl() === BAR_ID) {
        el.remove();
      }
    }
  }
}

编辑:有效的是运行手动设置 createbars 函数。幻灯片打开时,有没有办法运行这样做?

如果继续 View -> Executions,您将看到错误

Exception: Authorization is required to perform that action.at [unknown function](Code:3:30)
  • 这是因为你第3行的内容
    var presentation = SlidesApp.getActivePresentation();
    
    需要用户授权
  • 换句话说,这个变量不能是全局的,而是需要在用户手动运行的函数中定义——即两者都是function createBars()function deleteBars()
  • 还有:
    SlidesApp.getUi().createAddonMenu()
    
    仅适用于附加组件,用于从绑定脚本创建自定义菜单而不将其作为附加组件安装 - 使用
    SlidesApp.getUi().createMenu("my Menu")
    
    相反。