首页 > 解决方案 > 来自 HTML 的 google.script.run.function() 调用不起作用

问题描述

我正在从绑定到我的谷歌表的对话框 HTML 文件中调用一个函数。我从谷歌开发中复制了代码并想调用一个简单的函数。但是,它什么也没做。我尝试了各种方法,但我就是无法让它发挥作用。脚本和 HTML 都绑定到我的电子表格。

这是我的脚本:

// Use this code for Google Docs, Slides, Forms, or Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .createMenu('Dialog')
      .addItem('Open', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('Index');
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

function doSomething() {
  Logger.log('I was called!');
}

这是简单的 HTML 文件

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      google.script.run.doSomething();
    </script>
  </head>
</html>

标签: google-apps-scriptgoogle-sheets

解决方案


试试这个:GS:

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('ah3');
  SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
}

function doSomething() {
  SpreadsheetApp.getActive().toast("I was called.")
}

HTML:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      window.onload=function(){
        google.script.run
        .withSuccessHandler(function(){google.script.host.close();})
        .doSomething();
      }
      console.log("I am here");
    </script>
  </head>
  <body>
  </body>
</html>

推荐阅读