Google Workspace 文档中的对话框和边栏

绑定到 Google 文档、表格或表单的脚本可以显示多种类型的界面元素,包括预构建的提醒和提示,以及包含自定义 HTML 服务页面的对话框和边栏。通常,这些元素通过菜单项打开。(请注意,在 Google 表单中,只有打开表单进行修改的编辑者才能看到界面元素,而打开表单进行回复的用户则看不到。)

提醒对话框

提醒是一种预构建的对话框,会在 Google 文档、表格、幻灯片或 Google 表单编辑器中打开。它会显示一条消息和一个“确定”按钮;标题和其他按钮是可选的。这类似于在网络浏览器中的客户端 JavaScript 中调用 window.alert()

提醒会在对话框打开期间暂停服务器端脚本。脚本会在用户关闭对话框后恢复,但 JDBC 连接不会在暂停期间保留。

如下例所示,Google 文档、表单、幻灯片和表格均使用 Ui.alert() 方法,该方法有三种变体。如需替换默认的“确定”按钮,请将 Ui.ButtonSet 枚举中的值作为 buttons 参数传递。如需评估用户点击了哪个按钮,请将 alert() 的返回值与 Ui.Button 枚举进行比较。

function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
    .createMenu("Custom Menu")
    .addItem("Show alert", "showAlert")
    .addToUi();
}

function showAlert() {
  var ui = SpreadsheetApp.getUi(); // Same variations.

  var result = ui.alert(
    "Please confirm",
    "Are you sure you want to continue?",
    ui.ButtonSet.YES_NO,
  );

  // Process the user's response.
  if (result == ui.Button.YES) {
    // User clicked "Yes".
    ui.alert("Confirmation received.");
  } else {
    // User clicked "No" or X in the title bar.
    ui.alert("Permission denied.");
  }
}

提示对话框

提示是指在 Google 文档、表格、幻灯片或 Google 表单编辑器中打开的预构建对话框。它会显示一条消息、一个文本输入字段和一个“确定”按钮;标题和其他按钮是可选的。这类似于在网络浏览器中的客户端 JavaScript 中调用 window.prompt()

提示在对话框打开期间暂停服务器端脚本。该脚本会在用户关闭对话框后恢复,但 JDBC 连接在暂停期间不会保留。

如以下示例所示,Google 文档、表单、幻灯片和表格都使用 Ui.prompt() 方法,该方法有三种变体。如需替换默认的“确定”按钮,请将 Ui.ButtonSet 枚举中的值作为 buttons 参数传递。如需评估用户的响应,请捕获 prompt() 的返回值,然后调用 PromptResponse.getResponseText() 来检索用户的输入,并将 PromptResponse.getSelectedButton() 的返回值与 Ui.Button 枚举进行比较。

function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
    .createMenu("Custom Menu")
    .addItem("Show prompt", "showPrompt")
    .addToUi();
}

function showPrompt() {
  var ui = SpreadsheetApp.getUi(); // Same variations.

  var result = ui.prompt(
    "Let's get to know each other!",
    "Please enter your name:",
    ui.ButtonSet.OK_CANCEL,
  );

  // Process the user's response.
  var button = result.getSelectedButton();
  var text = result.getResponseText();
  if (button == ui.Button.OK) {
    // User clicked "OK".
    ui.alert("Your name is " + text + ".");
  } else if (button == ui.Button.CANCEL) {
    // User clicked "Cancel".
    ui.alert("I didn't get your name.");
  } else if (button == ui.Button.CLOSE) {
    // User clicked X in the title bar.
    ui.alert("You closed the dialog.");
  }
}

自定义对话框

自定义对话框可以在 Google 文档、表格、幻灯片或表单编辑器中显示 HTML 服务界面。

当自定义对话框打开时,它不会挂起服务器端脚本。客户端组件可以使用适用于 HTML 服务接口的 google.script API 对服务器端脚本进行异步调用。

该对话框可以通过在 HTML 服务接口的客户端调用 google.script.host.close() 自行关闭。其他界面无法关闭该对话框,只有用户或该对话框本身可以关闭。

如以下示例所示,Google 文档、表单、幻灯片和表格都使用 Ui.showModalDialog() 方法打开对话框。

Code.gs

function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .createMenu('Custom Menu')
      .addItem('Show dialog', 'showDialog')
      .addToUi();
}

function showDialog() {
  var html = HtmlService.createHtmlOutputFromFile('Page')
      .setWidth(400)
      .setHeight(300);
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .showModalDialog(html, 'My custom dialog');
}

Page.html

Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />

自定义边栏

侧边栏可以在 Google 文档、表单、幻灯片和表格编辑器中显示 HTML 服务界面。

当对话框打开时,边栏不会暂停服务器端脚本。客户端组件可以使用适用于 HTML 服务接口的 google.script API 对服务器端脚本进行异步调用。

边栏可以在 HTML 服务接口的客户端中通过调用 google.script.host.close() 自行关闭。边栏无法由其他界面关闭,只能由用户或自身关闭。

如以下示例所示,Google 文档、表单、幻灯片和表格都使用 Ui.showSidebar() 方法打开边栏。

Code.gs

function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .createMenu('Custom Menu')
      .addItem('Show sidebar', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('Page')
      .setTitle('My custom sidebar');
  SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
      .showSidebar(html);
}

Page.html

Hello, world! <input type="button" value="Close" onclick="google.script.host.close()" />

文件打开对话框

Google Picker 是一种 JavaScript API,可让用户选择或上传 Google 云端硬盘文件。Google Picker 库可在 HTML 服务中使用,用于创建自定义对话框,让用户选择现有文件或上传新文件,然后将所选内容传回脚本以供进一步使用。

要求

若要将 Google 选择器与 Apps Script 搭配使用,您需要满足多项要求。

示例

以下示例展示了 Apps Script 中的 Google Picker。

code.gs

Picker/code.gs
/**
 * Creates a custom menu in Google Sheets when the spreadsheet opens.
 */
function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu("Picker")
    .addItem("Start", "showPicker")
    .addToUi();
}

/**
 * Displays an HTML-service dialog in Google Sheets that contains client-side
 * JavaScript code for the Google Picker API.
 */
function showPicker() {
  const html = HtmlService.createHtmlOutputFromFile("dialog.html")
    .setWidth(800)
    .setHeight(600)
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi().showModalDialog(html, "Select a file");
}
/**
 * Checks that the file can be accessed.
 */
function getFile(fileId) {
  return Drive.Files.get(fileId, { fields: "*" });
}

/**
 * Gets the user's OAuth 2.0 access token so that it can be passed to Picker.
 * This technique keeps Picker from needing to show its own authorization
 * dialog, but is only possible if the OAuth scope that Picker needs is
 * available in Apps Script. In this case, the function includes an unused call
 * to a DriveApp method to ensure that Apps Script requests access to all files
 * in the user's Drive.
 *
 * @return {string} The user's OAuth 2.0 access token.
 */
function getOAuthToken() {
  return ScriptApp.getOAuthToken();
}

dialog.html

picker/dialog.html
<!DOCTYPE html>
<html>
  <head>
    <link
      rel="stylesheet"
      href="https://ssl.gstatic.com/docs/script/css/add-ons.css"
    />
    <style>
      #result {
        display: flex;
        flex-direction: column;
        gap: 0.25em;
      }

      pre {
        font-size: x-small;
        max-height: 25vh;
        overflow-y: scroll;
        background: #eeeeee;
        padding: 1em;
        border: 1px solid #cccccc;
      }
    </style>
    <script>
      // TODO: Replace the value for DEVELOPER_KEY with the API key obtained
      // from the Google Developers Console.
      const DEVELOPER_KEY = "AIza...";
      // TODO: Replace the value for CLOUD_PROJECT_NUMBER with the project
      // number obtained from the Google Developers Console.
      const CLOUD_PROJECT_NUMBER = "1234567890";

      let pickerApiLoaded = false;
      let oauthToken;

      /**
       * Loads the Google Picker API.
       */
      function onApiLoad() {
        gapi.load("picker", {
          callback: function () {
            pickerApiLoaded = true;
          },
        });
      }

      /**
       * Gets the user's OAuth 2.0 access token from the server-side script so that
       * it can be passed to Picker. This technique keeps Picker from needing to
       * show its own authorization dialog, but is only possible if the OAuth scope
       * that Picker needs is available in Apps Script. Otherwise, your Picker code
       * will need to declare its own OAuth scopes.
       */
      function getOAuthToken() {
        google.script.run
          .withSuccessHandler((token) => {
            oauthToken = token;
            createPicker(token);
          })
          .withFailureHandler(showError)
          .getOAuthToken();
      }

      /**
       * Creates a Picker that can access the user's spreadsheets. This function
       * uses advanced options to hide the Picker's left navigation panel and
       * default title bar.
       *
       * @param {string} token An OAuth 2.0 access token that lets Picker access the
       *     file type specified in the addView call.
       */
      function createPicker(token) {
        document.getElementById("result").innerHTML = "";

        if (pickerApiLoaded && token) {
          const picker = new google.picker.PickerBuilder()
            // Instruct Picker to display only spreadsheets in Drive. For other
            // views, see https://developers.google.com/picker/reference/picker.viewid
            .addView(
              new google.picker.DocsView(
                google.picker.ViewId.SPREADSHEETS
              ).setOwnedByMe(true)
            )
            // Hide the navigation panel so that Picker fills more of the dialog.
            .enableFeature(google.picker.Feature.NAV_HIDDEN)
            // Hide the title bar since an Apps Script dialog already has a title.
            .hideTitleBar()
            .setOAuthToken(token)
            .setDeveloperKey(DEVELOPER_KEY)
            .setAppId(CLOUD_PROJECT_NUMBER)
            .setCallback(pickerCallback)
            .setOrigin(google.script.host.origin)
            .build();
          picker.setVisible(true);
        } else {
          showError("Unable to load the file picker.");
        }
      }

      /**
       * A callback function that extracts the chosen document's metadata from the
       * response object. For details on the response object, see
       * https://developers.google.com/picker/reference/picker.responseobject
       *
       * @param {object} data The response object.
       */
      function pickerCallback(data) {
        const action = data[google.picker.Response.ACTION];
        if (action == google.picker.Action.PICKED) {
          handlePicked(data);
        } else if (action == google.picker.Action.CANCEL) {
          document.getElementById("result").innerHTML = "Picker canceled.";
        }
      }

      /**
       * Handles `"PICKED"` responsed from the Google Picker.
       *
       * @param {object} data The response object.
       */
      function handlePicked(data) {
        const doc = data[google.picker.Response.DOCUMENTS][0];
        const id = doc[google.picker.Document.ID];

        google.script.run
          .withSuccessHandler((driveFilesGetResponse) => {
            // Render the response from Picker and the Drive.Files.Get API.
            const resultElement = document.getElementById("result");
            resultElement.innerHTML = "";

            for (const response of [
              {
                title: "Picker response",
                content: JSON.stringify(data, null, 2),
              },
              {
                title: "Drive.Files.Get response",
                content: JSON.stringify(driveFilesGetResponse, null, 2),
              },
            ]) {
              const titleElement = document.createElement("h3");
              titleElement.appendChild(document.createTextNode(response.title));
              resultElement.appendChild(titleElement);

              const contentElement = document.createElement("pre");
              contentElement.appendChild(
                document.createTextNode(response.content)
              );
              resultElement.appendChild(contentElement);
            }
          })
          .withFailureHandler(showError)
          .getFile(data[google.picker.Response.DOCUMENTS][0].id);
      }

      /**
       * Displays an error message within the #result element.
       *
       * @param {string} message The error message to display.
       */
      function showError(message) {
        document.getElementById("result").innerHTML = "Error: " + message;
      }
    </script>
  </head>

  <body>
    <div>
      <button onclick="getOAuthToken()">Select a file</button>
      <div id="result"></div>
    </div>
    <script src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
  </body>
</html>

appsscript.json

picker/appsscript.json
{
    "timeZone": "America/Los_Angeles",
    "exceptionLogging": "STACKDRIVER",
    "runtimeVersion": "V8",
    "oauthScopes": [
      "https://www.googleapis.com/auth/script.container.ui",
      "https://www.googleapis.com/auth/drive.file"
    ],
    "dependencies": {
      "enabledAdvancedServices": [
        {
          "userSymbol": "Drive",
          "version": "v3",
          "serviceId": "drive"
        }
      ]
    }
  }