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 服務使用者介面。

自訂對話方塊「不會」在對話方塊開啟時暫停伺服器端指令碼。 用戶端元件可以使用 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」是「開啟檔案」對話方塊,用於記錄儲存在 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 金鑰旁邊,依序點選「更多」圖示 「更多」圖示>「編輯 API 金鑰」
  7. 在「應用程式限制」下方,完成下列步驟:

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

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

      注意:您必須先啟用 Google Picker API,畫面上才會顯示 Google Picker API,因為清單只會顯示 Cloud 專案已啟用的 API。

  9. 按一下「API 金鑰」下方的「複製到剪貼簿」圖示 「複製到剪貼簿」圖示

  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);
  }
}

dialog.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>