Google Workspace Dokümanlarındaki İletişim Kutuları ve Kenar Çubukları

Google Dokümanlar, E-Tablolar veya Formlar'a bağlı komut dosyaları, önceden oluşturulmuş uyarılar ve istemler ile özel HTML hizmeti sayfaları içeren iletişim kutuları ve kenar çubukları gibi çeşitli kullanıcı arayüzü öğelerini görüntüleyebilir. Genellikle bu öğeler menü öğelerinden açılır. (Google Formlar'da kullanıcı arayüzü öğelerinin, yalnızca formu değiştirmek için formu açan bir düzenleyici tarafından görülebildiğini, yanıt vermek için formu açan kullanıcının görünmediğini unutmayın.)

Uyarı iletişim kutuları

Uyarı; Google Dokümanlar, E-Tablolar, Slaytlar veya Formlar düzenleyicilerinde açılan önceden oluşturulmuş bir iletişim kutusudur. Bir mesaj ve "Tamam" düğmesi görüntülenir. Başlık ve alternatif düğmeler isteğe bağlıdır. Bir web tarayıcısında istemci taraflı JavaScript'te window.alert() çağrısına benzer.

Uyarılar, iletişim kutusu açıkken sunucu tarafı komut dosyasını askıya alır. Kullanıcı iletişim kutusunu kapattıktan sonra komut dosyası devam eder ancak JDBC bağlantıları askıya alma süresi boyunca devam etmez.

Aşağıdaki örnekte gösterildiği gibi Google Dokümanlar, Formlar, Slaytlar ve E-Tablolar'ın tümü, üç varyant halinde sunulan Ui.alert() yöntemini kullanmaktadır. Varsayılan "Tamam" düğmesini geçersiz kılmak için Ui.ButtonSet sıralamasından buttons bağımsız değişkeni olarak bir değer iletin. Kullanıcının hangi düğmeyi tıkladığını değerlendirmek için alert() işlevinin döndürülen değerini Ui.Button sıralamasıyla karşılaştırın.

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

İstem iletişim kutuları

İstem; Google Dokümanlar, E-Tablolar, Slaytlar veya Formlar düzenleyicilerinde açılan önceden oluşturulmuş bir iletişim kutusudur. Burada bir mesaj, metin giriş alanı ve "Tamam" düğmesi görüntülenir. Başlık ve alternatif düğmeler isteğe bağlıdır. Bir web tarayıcısında istemci taraflı JavaScript'te window.prompt() çağrısına benzer.

İstemler, iletişim kutusu açıkken sunucu tarafı komut dosyasını askıya alır. Kullanıcı iletişim kutusunu kapattıktan sonra komut dosyası devam eder ancak JDBC bağlantıları askıya alma süresi boyunca devam etmez.

Aşağıdaki örnekte gösterildiği gibi Google Dokümanlar, Formlar, Slaytlar ve E-Tablolar'ın tümü, üç varyant halinde sunulan Ui.prompt() yöntemini kullanır. Varsayılan "Tamam" düğmesini geçersiz kılmak için Ui.ButtonSet sıralamasındaki bir değeri buttons bağımsız değişkeni olarak iletin. Kullanıcının yanıtını değerlendirmek için prompt() için döndürülen değeri yakalayın, ardından PromptResponse.getResponseText() çağrısıyla kullanıcının girişini alın ve PromptResponse.getSelectedButton() için döndürülen değeri Ui.Button sıralamasıyla karşılaştırın.

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

Özel iletişim kutuları

Özel iletişim kutuları; Google Dokümanlar, E-Tablolar, Slaytlar veya Formlar düzenleyicisinde HTML hizmeti kullanıcı arayüzü gösterebilir.

Özel iletişim kutuları, iletişim kutusu açıkken sunucu tarafı komut dosyasını askıya almaz. İstemci tarafı bileşeni, HTML hizmeti arayüzleri için google.script API'yi kullanarak sunucu tarafı komut dosyasına eşzamansız çağrılar yapabilir.

İletişim kutusu, HTML hizmeti arayüzünün istemci tarafında google.script.host.close() çağrısı yaparak kendi kendini kapatabilir. İletişim kutusu diğer arayüzler tarafından, yalnızca kullanıcı veya kendisi tarafından kapatılamaz.

Aşağıdaki örnekte gösterildiği gibi Google Dokümanlar, Formlar, Slaytlar ve E-Tablolar'ın tümü, iletişim kutusunu açmak için Ui.showModalDialog() yöntemini kullanır.

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()" />

Özel kenar çubukları

Bir kenar çubuğu; Google Dokümanlar, Formlar, Slaytlar ve E-Tablolar düzenleyicisi içinde bir HTML hizmeti kullanıcı arayüzü gösterebilir.

Kenar çubukları, iletişim kutusu açıkken sunucu tarafı komut dosyasını askıya almaz. İstemci tarafı bileşeni, HTML hizmeti arayüzleri için google.script API'yi kullanarak sunucu tarafı komut dosyasına eşzamansız çağrılar yapabilir.

Kenar çubuğu, HTML hizmeti arayüzünün istemci tarafında google.script.host.close() yöntemini çağırarak kendi kendini kapatabilir. Kenar çubuğu diğer arayüzler tarafından, yalnızca kullanıcı veya kendisi tarafından kapatılamaz.

Aşağıdaki örnekte gösterildiği gibi Google Dokümanlar, Formlar, Slaytlar ve E-Tablolar'ın tümü, kenar çubuğunu açmak için Ui.showSidebar() yöntemini kullanır.

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()" />

Dosya açma iletişim kutuları

Google Picker, Google Drive, Google Görsel Arama, Google Video Arama ve daha fazlası dahil olmak üzere Google sunucularında depolanan bilgiler için "dosya açma" iletişim kutusudur.

Aşağıdaki örnekte gösterildiği gibi, Picker'ın istemci tarafı JavaScript API'si HTML hizmetinde kullanıcıların mevcut dosyaları seçmelerine veya yeni dosyalar yüklemelerine, ardından bu seçimi daha sonra kullanılmak üzere komut dosyanıza geri iletmelerine olanak tanıyan özel bir iletişim kutusu oluşturmak için kullanılabilir.

Seçici'yi etkinleştirmek ve bir API anahtarı almak için şu talimatları uygulayın:

  1. Komut dosyası projenizin standart GCP projesi kullandığını doğrulayın.
  2. Google Cloud projenizde "Google Picker API"yi etkinleştirin.
  3. Google Cloud projeniz hâlâ açıkken API'ler ve Hizmetler'i seçin, ardından Kimlik bilgileri'ni tıklayın.
  4. Kimlik bilgileri oluştur > API anahtarı'nı tıklayın. Bu işlem, anahtarı oluşturur ancak anahtara hem uygulama kısıtlamaları hem de bir API kısıtlaması eklemek için anahtarı düzenlemeniz gerekir.
  5. API anahtarı iletişim kutusunda Kapat'ı tıklayın.
  6. Oluşturduğunuz API anahtarının yanında, Diğer Diğer simgesi> API anahtarını düzenle'yi tıklayın.
  7. Uygulama kısıtlamaları bölümünde aşağıdaki adımları tamamlayın:

    1. HTTP yönlendirenler (web siteleri) seçeneğini belirleyin.
    2. Web sitesi kısıtlamaları bölümünde Öğe ekleyin'i tıklayın.
    3. Yönlendiren'i tıklayın ve *.google.com değerini girin.
    4. Başka bir öğe ekleyin ve yönlendiren olarak *.googleusercontent.com değerini girin.
    5. Done'ı (Bitti) tıklayın.
  8. API kısıtlamaları bölümünde, aşağıdaki adımları tamamlayın:

    1. Anahtarı kısıtla'yı seçin.
    2. API'leri seçin bölümünde Google Picker API'yi seçin ve Tamam'ı tıklayın.

      Not: Listede yalnızca Cloud projesi için etkinleştirilen API'ler gösterildiğinden, Google Picker API siz etkinleştirmediğiniz sürece görünmez.

  9. API anahtarı altında, Panoya kopyala simgesini Panoya kopyala simgesi tıklayın.

  10. En alttaki Kaydet'i tıklayın.

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>