Google Workspace 문서의 대화상자 및 사이드바

Google Docs, Sheets, Forms에 결합된 스크립트는 여러 유형의 사용자 인터페이스 요소(사전 빌드된 알림 및 메시지, 맞춤 HTML 서비스 페이지가 포함된 대화상자 및 사이드바)를 표시할 수 있습니다. 일반적으로 이러한 요소는 메뉴 항목에서 열립니다. (Google Forms에서 사용자 인터페이스 요소는 응답하기 위해 양식을 연 사용자가 아니라 양식을 수정하기 위해 양식을 연 편집자에게만 표시됩니다.)

알림 대화상자

알림은 Google Docs, Sheets, Slides 또는 Forms 편집기 내에서 열리는 사전 빌드된 대화상자입니다. 메시지와 '확인' 버튼이 표시됩니다. 제목과 대체 버튼은 선택사항입니다. 이는 웹브라우저의 클라이언트 측 JavaScript에서 window.alert()를 호출하는 것과 유사합니다.

알림은 대화상자가 열려 있는 동안 서버 측 스크립트를 정지합니다. 스크립트는 사용자가 대화상자를 닫은 후에 다시 시작되지만 정지 기간 동안에는 JDBC 연결이 유지되지 않습니다.

아래 예에서 볼 수 있듯이 Google Docs, Forms, Slides, Sheets는 모두 세 가지 변형으로 제공되는 Ui.alert() 메서드를 사용합니다. 기본 'OK' 버튼을 재정의하려면 Ui.ButtonSet enum의 값을 buttons 인수로 전달합니다. 사용자가 클릭한 버튼을 평가하려면 alert()의 반환 값을 Ui.Button enum과 비교합니다.

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 편집기 내에서 열리는 사전 빌드된 대화상자입니다. 메시지, 텍스트 입력란, '확인' 버튼이 표시됩니다. 제목과 대체 버튼은 선택사항입니다. 이는 웹브라우저의 클라이언트 측 JavaScript에서 window.prompt()를 호출하는 것과 유사합니다.

프롬프트는 대화상자가 열려 있는 동안 서버 측 스크립트를 정지합니다. 스크립트는 사용자가 대화상자를 닫은 후에 다시 시작되지만 정지 기간 동안에는 JDBC 연결이 유지되지 않습니다.

아래 예에서 볼 수 있듯이 Google Docs, Forms, Slides, Sheets는 모두 세 가지 변형으로 제공되는 Ui.prompt() 메서드를 사용합니다. 기본 'OK' 버튼을 재정의하려면 Ui.ButtonSet enum의 값을 buttons 인수로 전달합니다. 사용자의 응답을 평가하려면 prompt()의 반환 값을 캡처한 다음 PromptResponse.getResponseText()를 호출하여 사용자의 입력을 검색하고 PromptResponse.getSelectedButton()의 반환 값을 Ui.Button enum과 비교합니다.

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 Docs, Sheets, Slides, Forms 편집기 내의 HTML 서비스 사용자 인터페이스를 표시할 수 있습니다.

맞춤 대화상자는 대화상자가 열려 있는 동안에는 서버 측 스크립트를 정지하지 않습니다. 클라이언트 측 구성요소는 HTML 서비스 인터페이스에 google.script API를 사용하여 서버 측 스크립트를 비동기식으로 호출할 수 있습니다.

대화상자는 HTML 서비스 인터페이스의 클라이언트 측에서 google.script.host.close()를 호출하여 자체적으로 닫힐 수 있습니다. 이 대화상자는 다른 인터페이스에서 닫을 수 없고 사용자 또는 그 자체에서만 닫을 수 있습니다.

아래 예와 같이 Google Docs, Forms, Slides, Sheets는 모두 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 Docs, Forms, Slides, Sheets 편집기 내의 HTML 서비스 사용자 인터페이스를 표시할 수 있습니다.

사이드바는 대화상자가 열려 있는 동안 서버 측 스크립트를 정지하지 않습니다. 클라이언트 측 구성요소는 HTML 서비스 인터페이스에 google.script API를 사용하여 서버 측 스크립트를 비동기식으로 호출할 수 있습니다.

사이드바는 HTML 서비스 인터페이스의 클라이언트 측에서 google.script.host.close()를 호출하여 자체적으로 닫을 수 있습니다. 사이드바는 다른 인터페이스에서 닫을 수 없고 사용자 자체에서만 닫을 수 있습니다.

아래 예와 같이 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 선택 도구는 Google 드라이브, Google 이미지 검색, Google 동영상 검색 등의 Google 서버에 저장된 정보를 위한 '파일 열기' 대화상자입니다.

아래 예와 같이 선택 도구의 클라이언트 측 JavaScript API를 HTML 서비스에서 사용하여 사용자가 기존 파일을 선택하거나 새 파일을 업로드한 후 이 선택 항목을 스크립트에 다시 전달하여 사용할 수 있는 맞춤 대화상자를 만들 수 있습니다.

선택 도구를 사용 설정하고 API 키를 가져오려면 다음 안내를 따르세요.

  1. 스크립트 프로젝트가 표준 GCP 프로젝트를 사용하고 있는지 확인합니다.
  2. Google Cloud 프로젝트에서 'Google Picker API' 사용 설정
  3. Google Cloud 프로젝트가 열려 있는 상태에서 API 및 서비스를 선택한 다음 사용자 인증 정보를 클릭합니다.
  4. 사용자 인증 정보 만들기 > API 키를 클릭합니다. 이 작업으로 키가 생성되지만 키에서 애플리케이션 제한사항과 API 제한사항을 모두 추가하려면 키를 수정해야 합니다.
  5. API 키 대화상자에서 닫기를 클릭합니다.
  6. 만든 API 키 옆의 더보기 더보기 아이콘> API 키 수정을 클릭합니다.
  7. 애플리케이션 제한사항에서 다음 단계를 완료합니다.

    1. HTTP 리퍼러 (웹사이트)를 선택합니다.
    2. 웹사이트 제한사항에서 항목 추가를 클릭합니다.
    3. 리퍼러를 클릭하고 *.google.com를 입력합니다.
    4. 다른 항목을 추가하고 리퍼러로 *.googleusercontent.com를 입력합니다.
    5. 완료를 클릭합니다.
  8. API 제한사항에서 다음 단계를 완료합니다.

    1. 키 제한을 선택합니다.
    2. API 선택 섹션에서 Google Picker API를 선택하고 확인을 클릭합니다.

      참고: 목록에는 Cloud 프로젝트에 사용 설정된 API만 표시되므로 사용 설정하지 않으면 Google Picker 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>