繁体   English   中英

HTML Google 表格 google.script.run 中的对话框。 无法运行 Apps 脚本 function

[英]HTML Dialog in Google Sheets google.script.run. fails to run Apps Script function

我正在使用 Google 表格与一位年长的朋友进行远程游戏(经游戏发行商许可)。

我正在尝试使用带有按钮的 HTML 对话框来触发一些脚本。 我已经完成了我可以在文档和 Yagisanatode 的博客中找到的所有示例。 除了google.script.run.addEgg()没有触发 Code.gs 中的addEgg() function 之外,这一切都有效。

我包括相关的代码位。 在进一步构建之前,我正在努力让一个按钮触发一个脚本。

EggFoodTuck01() ,通过单击ObjectOverGrid触发,成功启动对话框

function EggFoodTuck01(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName('Decks'));
  sheet.getRange('CurrentCard').setValue(0); // Record Card Number in 'CurrentCard' Cell (0-14)
  sheet.getRange('CurrentSheet').setValue('Player 1'); // Record Sheet Name in 'CurrentSheet'
  
  // Launch dialog
  var html = HtmlService.createHtmlOutputFromFile("EFTDialog");
  ui.showModalDialog(html, "What would you like to do?");
}

HTML 对话框正确显示。 单击 [+ Egg] 按钮会启动actionAddEgg() ,因为对话框会关闭。 无论出于何种原因, addEgg()都没有在我的 Apps 脚本中运行。

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
  </head>
  <body>
  <div>
    <br>
    <br>
    <input type="button" value="+ 🥚" class="share" onclick="addEgg()" />
    <br>
    <br>
    <input type="button" value="Cancel" class="action" onclick="google.script.host.close()" />
  </div>
    <script>
    function addEgg(){
    google.script.run.addEgg();
    google.script.host.close();
    }
    </script>
  </body>
</html>

这是 Apps 脚本中的addEgg() 它根本没有运行。 'card' 变量甚至不会记录。

function addEgg(){
  // Get card and sheet data
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName('Decks'));
  var card = sheet.getRange('CurrentCard').getValue();
  var sheetname = sheet.getRange('CurrentSheet').getValue();
  var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName(sheetname));
  
  // Get current egg value and +1
  var eggCell = ['F7','M7','T7','AA7','AH7','F16','M16','T16','AA16','AH16','F25','M25','T25','AA25','AH25'];
  var egg = sheet.getRange(eggCell[card]).getValue();
  sheet.getRange(eggCell[card]).setValue(egg + 1);
}

你错过了google.script.run是异步的。 这意味着google.script.host.close()可能在google.script.run.addEgg()调用被有效执行之前执行。

一种选择是您使用withSuccessHandler调用google.script.host.close()

您缺少的另一件事是google.script.run将使用用于登录 Google 服务的默认帐户执行。 一种快速的解决方案是与您的默认帐户共享您的电子表格。

有关的

  • 您不应该对服务器和客户端脚本函数使用相同的 function 名称 ( addEgg )。 考虑更改其中一个函数的名称。

  • successHandler中使用close因为google.script.run是异步的。 这个答案中提到了这一点

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM