Google Workspace 文件中的對話方塊和側欄

與 Google 文件、試算表或表單繫結的指令碼可顯示多種使用者介面元素,包括預先建立的快訊和提示,以及含有自訂 HTML 服務頁面的對話方塊和側欄。這些元素通常可從選單項目開啟。(請注意,在 Google 表單中,只有開啟表單進行修改的使用者介面元素,才能看到開啟表單並回覆的使用者)。

快訊對話方塊

快訊是預先建立的對話方塊,會在 Google 文件、試算表、簡報或表單編輯器中開啟。系統會顯示訊息和「確定」按鈕;標題和替代按鈕為選填。這類似於在網路瀏覽器的用戶端 JavaScript 中呼叫 window.alert()

對話方塊開啟時,快訊會暫停伺服器端指令碼。這個指令碼會在使用者關閉對話方塊後恢復,但暫停期間不會保留 JDBC 連線。

如以下範例所示,Google 文件、表單、簡報和試算表均使用 Ui.alert() 方法,方法有三種。如要覆寫預設的「OK」按鈕,請從 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 文件、試算表、簡報或表單編輯器中開啟。系統會顯示訊息、文字輸入欄位和「確定」按鈕;您可以選擇是否提供標題和替代按鈕。這類似於在網路瀏覽器的用戶端 JavaScript 中呼叫 window.prompt()

對話方塊開啟時,提示會暫停伺服器端指令碼。這個指令碼會在使用者關閉對話方塊後恢復,但暫停期間不會保留 JDBC 連線。

如以下範例所示,Google 文件專業表單、簡報和試算表均使用 Ui.prompt() 方法,方法有三種變化版本。如要覆寫預設的「OK」按鈕,請從 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 服務使用者介面。

對話方塊開啟時,自訂對話方塊「不會」暫停伺服器端指令碼。 用戶端元件可使用 google.script API,針對 HTML 服務介面進行非同步呼叫伺服器端指令碼。

對話方塊可能會在 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');
}

網頁.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);
}

網頁.html

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

開啟檔案的對話方塊

Google Picker 是「檔案開啟」對話方塊,用於儲存 Google 伺服器 (包括 Google 雲端硬碟、Google 圖片搜尋、Google 影片搜尋等) 中的資訊。

如下方範例所示,您可以在 HTML 服務中使用 Picker 的用戶端 JavaScript API 建立自訂對話方塊,讓使用者選取現有檔案或上傳新檔案,然後將選取內容傳回指令碼以供日後使用。

如要啟用 Picker 及取得 API 金鑰,請按照下列操作說明進行:

  1. 確認指令碼專案使用的是標準 GCP 專案
  2. 在 Google Cloud 專案中啟用「Google Picker API」
  3. Google Cloud 專案仍處於開啟狀態時,依序選取「APIs & Services」(API 和服務) 和「Credentials」(憑證)
  4. 依序點選「建立憑證」>「API 金鑰」。這項操作會建立金鑰,但您應編輯該金鑰,以便同時設定應用程式限制和 API 限制。
  5. 在 API 金鑰對話方塊中,按一下「關閉」
  6. 在您建立的 API 金鑰旁邊,依序按一下「More」(更多) 圖示 「更多」圖示>「Edit API key」(編輯 API 金鑰)
  7. 在「應用程式限制」下方,完成下列步驟:

    1. 選取「HTTP 參照網址 (網站)」
    2. 在「網站限制」下方,按一下「新增項目」
    3. 按一下「Referrer」並輸入 *.google.com
    4. 新增其他商品,然後輸入 *.googleusercontent.com 做為參照網址。
    5. 點選「完成」
  8. 在「API 限制」下方,完成下列步驟:

    1. 選取「限制金鑰」
    2. 在「選取 API」區段中,選取「Google Picker API」,然後按一下「確定」

      注意:只有在您已啟用 Cloud 專案並啟用的 API 時,Google Picker API 才會顯示。

  9. 在「API key」(API 金鑰) 下方,按一下「Copy to clipboard」(複製到剪貼簿) 「複製到剪貼簿」圖示

  10. 按一下底部的 [儲存]。

code.gs

Picker/code.gs
/**
 * Creates a custom menu in Google Sheets when the spreadsheet opens.
 */
function onOpen() {
  try {
    SpreadsheetApp.getUi().createMenu('Picker')
        .addItem('Start', 'showPicker')
        .addToUi();
  } catch (e) {
    // TODO (Developer) - Handle exception
    console.log('Failed with error: %s', e.error);
  }
}

/**
 * Displays an HTML-service dialog in Google Sheets that contains client-side
 * JavaScript code for the Google Picker API.
 */
function showPicker() {
  try {
    const html = HtmlService.createHtmlOutputFromFile('dialog.html')
        .setWidth(600)
        .setHeight(425)
        .setSandboxMode(HtmlService.SandboxMode.IFRAME);
    SpreadsheetApp.getUi().showModalDialog(html, 'Select a file');
  } catch (e) {
    // TODO (Developer) - Handle exception
    console.log('Failed with error: %s', e.error);
  }
}

/**
 * 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() {
  try {
    DriveApp.getRootFolder();
    return ScriptApp.getOAuthToken();
  } catch (e) {
    // TODO (Developer) - Handle exception
    console.log('Failed with error: %s', e.error);
  }
}

對話方塊.html

Picker/dialog.html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
  <script>
    // IMPORTANT: Replace the value for DEVELOPER_KEY with the API key obtained
    // from the Google Developers Console.
    var DEVELOPER_KEY = 'ABC123 ... ';
    var DIALOG_DIMENSIONS = {width: 600, height: 425};
    var pickerApiLoaded = false;

    /**
     * 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(createPicker)
          .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) {
      if (pickerApiLoaded && token) {
        var picker = new google.picker.PickerBuilder()
            // Instruct Picker to display only spreadsheets in Drive. For other
            // views, see https://developers.google.com/picker/docs/#otherviews
            .addView(google.picker.ViewId.SPREADSHEETS)
            // 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)
            .setCallback(pickerCallback)
            .setOrigin(google.script.host.origin)
            // Instruct Picker to fill the dialog, minus 2 pixels for the border.
            .setSize(DIALOG_DIMENSIONS.width - 2,
                DIALOG_DIMENSIONS.height - 2)
            .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/docs/result
     *
     * @param {object} data The response object.
     */
    function pickerCallback(data) {
      var action = data[google.picker.Response.ACTION];
      if (action == google.picker.Action.PICKED) {
        var doc = data[google.picker.Response.DOCUMENTS][0];
        var id = doc[google.picker.Document.ID];
        var url = doc[google.picker.Document.URL];
        var title = doc[google.picker.Document.NAME];
        document.getElementById('result').innerHTML =
            '<b>You chose:</b><br>Name: <a href="' + url + '">' + title +
            '</a><br>ID: ' + id;
      } else if (action == google.picker.Action.CANCEL) {
        document.getElementById('result').innerHTML = 'Picker canceled.';
      }
    }

    /**
     * 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>
    <p id="result"></p>
  </div>
  <script src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>