תיבות דו-שיח וסרגלי צד במסמכים של Google Workspace

סקריפטים שמקושרים ל-Google Docs, ל-Sheets או ל-Forms יכולים להציג כמה סוגים של רכיבים בממשק המשתמש: התראות והודעות מוגדרות מראש, וגם תיבות דו-שיח וסרגלי צד שמכילים דפים של שירות HTML בהתאמה אישית. בדרך כלל, הרכיבים האלה נפתחים מתוך פריטים בתפריט. (שימו לב שב-Google Forms, רכיבי ממשק משתמש גלויים רק למשתמש שפותח את הטופס כדי לשנות אותו, ולא למשתמש שפותח את הטופס כדי להגיב).

תיבות דו-שיח של התראות

התראה היא תיבת דו-שיח שנוצרה מראש בעורך Google Docs , Sheets , Slides או Forms. יוצגו בו הודעה ולחצן אישור. לא חייבים להוסיף כותרת ולחצנים חלופיים. התהליך הזה דומה להפעלה של window.alert() ב-JavaScript בצד הלקוח בדפדפן אינטרנט.

ההתראות משעות את הסקריפט בצד השרת כאשר תיבת הדו-שיח פתוחה. הסקריפט ממשיך אחרי שהמשתמש סוגר את תיבת הדו-שיח, אבל חיבורי JDBC לא נשמרים לאורך כל ההשעיה.

כפי שאפשר לראות בדוגמה שבהמשך, כל המסמכים, הטפסים, Slides, Slides ו-Sheets משתמשים ב-method 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 Docs, Sheets, Slides או Forms. יוצגו בה הודעה, שדה להזנת טקסט ולחצן 'אישור'. לא חייבים להוסיף כותרת ולחצנים חלופיים. התהליך הזה דומה להפעלה של window.prompt() ב-JavaScript בצד הלקוח בדפדפן אינטרנט.

ההנחיות משעות את הסקריפט בצד השרת כאשר תיבת הדו-שיח פתוחה. הסקריפט ממשיך אחרי שהמשתמש סוגר את תיבת הדו-שיח, אבל חיבורי JDBC לא נשמרים לאורך כל ההשעיה.

כפי שאפשר לראות בדוגמה שבהמשך, כל המסמכים, Slides, Sheets ו-Google Docs משתמשים בשיטה 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.');
  }
}

תיבות דו-שיח בהתאמה אישית

בתיבת דו-שיח מותאמת אישית אפשר להציג ממשק משתמש של שירות HTML בתוך עורך Google Docs , Sheets , Slides או Forms.

תיבות דו-שיח בהתאמה אישית לא משעות את הסקריפט בצד השרת כשתיבת הדו-שיח פתוחה. הרכיב בצד הלקוח יכול לבצע קריאות אסינכרוניות לסקריפט בצד השרת באמצעות ממשק ה-API של google.script לממשקי שירות HTML.

תיבת הדו-שיח יכולה לסגור את עצמה על ידי קריאה ל-google.script.host.close() בצד הלקוח של ממשק שירות HTML. אי אפשר לסגור את תיבת הדו-שיח באמצעות ממשקים אחרים, אלא רק על ידי המשתמש עצמו.

כפי שמוצג בדוגמה הבאה, כל המסמכים, הטפסים, Slides, Slides ו-Sheets משתמשים ב-method 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()" />

סרגלי צד בהתאמה אישית

בסרגל הצד אפשר להציג ממשק משתמש של שירות HTML בתוך עורך Google Docs, Forms, Slides ו-Sheets.

סרגלי צד לא משעים את הסקריפט בצד השרת כשתיבת הדו-שיח פתוחה. הרכיב בצד הלקוח יכול לבצע קריאות אסינכרוניות לסקריפט בצד השרת באמצעות ממשק ה-API של google.script לממשקי שירות HTML.

אפשר לסגור את סרגל הצד על ידי קריאה ל-google.script.host.close() בצד הלקוח של ממשק שירות HTML. אי אפשר לסגור את סרגל הצד באמצעות ממשקים אחרים, אלא רק על ידי המשתמש עצמו.

כפי שמוצג בדוגמה למטה, ב-Google Docs, Forms, Slides ו-Sheets משתמשים בשיטה 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 Drive, Google Image Search, Google Video Search ועוד.

כפי שמוצג בדוגמה שבהמשך, ניתן להשתמש ב-JavaScript API בצד הלקוח של Picker בשירות HTML כדי ליצור תיבת דו-שיח בהתאמה אישית, שמאפשרת למשתמשים לבחור קבצים קיימים או להעלות קבצים חדשים, ואז להעביר את הבחירה הזו לסקריפט לשימוש נוסף.

כדי להפעיל את Picker ולקבל מפתח API, פועלים לפי ההוראות הבאות:

  1. מוודאים שבפרויקט הסקריפט נעשה שימוש בפרויקט GCP סטנדרטי.
  2. מפעילים את Google Picker API בפרויקט ב-Google Cloud.
  3. בזמן שהפרויקט ב-Google Cloud עדיין פתוח, בוחרים באפשרות APIs & Services ולוחצים על Credentials.
  4. לוחצים על יצירת פרטי כניסה > מפתח API. הפעולה הזו יוצרת את המפתח, אבל צריך לערוך אותו כדי להוסיף למפתח גם הגבלות על אפליקציות וגם הגבלת API.
  5. בתיבת הדו-שיח של מפתח ה-API, לוחצים על Close.
  6. לצד מפתח ה-API שיצרתם, לוחצים על סמל האפשרויות הנוספות סמל האפשרויות הנוספות> עריכת מפתח API.
  7. בקטע הגבלות על אפליקציות, מבצעים את השלבים הבאים:

    1. בוחרים באפשרות גורמים מפנים מסוג HTTP (אתרי אינטרנט).
    2. בקטע הגבלות גישה לאתרים, לוחצים על הוספת פריט.
    3. לוחצים על מקור ההפניה (referrer) ומזינים *.google.com.
    4. צריך להוסיף עוד פריט ולהזין *.googleusercontent.com כגורם המפנה.
    5. לוחצים על סיום.
  8. בקטע הגבלות API, מבצעים את השלבים הבאים:

    1. בוחרים באפשרות הגבלת מפתח.
    2. בקטע Select APIs, בוחרים באפשרות Google Picker API ולוחצים על OK.

      הערה: ה-Google Picker API מופיע רק אם תפעילו אותו, כי ברשימה מוצגים רק ממשקי API שהופעלו בפרויקט Cloud.

  9. בקטע API key לוחצים על 'העתקה ללוח' סמל ההעתקה ללוח.

  10. בחלק התחתון של המסך, לוחצים על שמירה.

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>