异常:无法从此上下文调用 SpreadsheetApp.getUi()

Oma*_*mar 4 javascript modal-dialog google-sheets google-apps-script

过去 3 小时我一直被这个错误困在这里。

错误异常:无法从此上下文调用 SpreadsheetApp.getUi()。

我将不胜感激的帮助。

function onOpen(e) {
      var menu = SpreadsheetApp.getUi().createMenu("Refresh");//The error is here
      menu.addItem("Refresh Week", "menu");
      menu.addToUi();
    }
Run Code Online (Sandbox Code Playgroud)
//The same thing goes to this function as well
function menu(){
        //get the good week number
        var date = new Date();
        var wn = [(Math.floor(WEEKNUMBER(date))+3).toFixed(0)]
        do {  
            wn.push((wn[wn.length-1]-1).toFixed(0))
        } while(wn[wn.length-1] != 348);
        var line = "<select style='width:60px;height:40px;' id='select'>"
        for ( var x in wn ) 
          line +="<option>" + wn[x] + "</option>"
        line +="</select>"
        var ui = SpreadsheetApp.getUi();
        var html = HtmlService.createHtmlOutputFromFile('Selector')
            .setWidth(200)
            .setHeight(150).setContent("<div>"+line + "</div><br><div><button onclick='reset()'>Confirm</button></div><script>function reset(){var wn = document.getElementById('select').value;document.getElementsByTagName('Body')[0].style.cursor = 'wait';google.script.run.withSuccessHandler(function (){google.script.host.close();}).readWP2(wn);}</script>")
        SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
            .showModalDialog(html, 'Please select a week number');
}
Run Code Online (Sandbox Code Playgroud)

因此,当我创建一个变量并将其设置为时,SpreadsheetApp.getUi()我开始收到此错误,并且由于此错误,其余代码不再运行

在此输入图像描述

我正在使用 Google Apps 脚本。

Nik*_* J. 7

我相信您想要做的是创建一个类似于 JavaScript 弹出框的对话框。不幸的是,Apps Script 没有该功能。您需要首先将其绑定到 Google Sheets、Docs、Slides 或 Forms 文件,对话框将出现在这些应用程序上。

我能够通过在独立脚本上执行您的代码来复制您的问题。独立脚本是指未绑定到 Google 表格、文档、幻灯片、表单文件或 Google 协作平台的任何脚本。

独立示例:

在此输入图像描述

SpreadsheetApp.getUi(); 仅与打开的电子表格的当前实例的 UI 交互,并且仅当脚本绑定到电子表格时。

要解决您的问题,请确保:

  1. 创建电子表格。
  2. 选择菜单项“扩展”>“Apps 脚本”。
  3. 删除脚本编辑器中的所有代码并粘贴您的代码。
  4. 运行您的脚本并进行身份验证。

您的代码应该在电子表格菜单或 Apps 脚本中运行,但对话框将始终显示在电子表格上。

例子:

在此输入图像描述

在此输入图像描述

参考