javascript - 此上下文中的异常 : Cannot call SpreadsheetApp. getUi()

标签 javascript google-apps-script google-sheets modal-dialog

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

Error Exception: Cannot call SpreadsheetApp.getUi() from this context.

我将不胜感激。

function onOpen(e) {
      var menu = SpreadsheetApp.getUi().createMenu("Refresh");//The error is here
      menu.addItem("Refresh Week", "menu");
      menu.addToUi();
    }
//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');
}

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

enter image description here

我正在使用 Google Apps 脚本。

最佳答案

我相信您要做的是创建一个类似于 JavaScript 弹出框的对话框。不幸的是,Apps 脚本没有该功能。您需要先将其绑定(bind)到 Google 表格、文档、幻灯片或表单文件,对话框将出现在这些应用程序上。

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

独立示例:

enter image description here

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

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

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

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

示例:

enter image description here

enter image description here

引用资料

关于javascript - 此上下文中的异常 : Cannot call SpreadsheetApp. getUi(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70895185/

相关文章:

php - 关于如何创建 mysql webservice/api 的建议

javascript - 使用纯 JavaScript 监听具有特定内容的 POST 事件

javascript - 通过 console.log([...mapObject.entries()]) 将类似于控制台输出的 map 转换为字符串

google-apps-script - 在 Google 表格中插入新行或编辑行时添加时间戳

optimization - 优化 Google 脚本以隐藏列

javascript - 如何保存可拖动对象的位置

javascript - 向下滚动时,ScrollMagic 中的 .setClassToggle 不会删除类

google-apps-script - 从脚本分配传入 Google 电子表格脚本中的参数

google-apps-script - Google Apps 脚本 - 编辑器快捷方式 - CTRL+D

google-apps-script - 带编码的 Google Sheets IMPORTDATA