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

Google Docs에 결합된 스크립트 Sheets 또는 Forms에서는 여러 유형의 사용자 인터페이스 요소를 표시할 수 있습니다. 사전 빌드된 알림과 프롬프트, 그리고 사용자 정의 기능이 포함된 HTML 서비스 페이지에서 사용할 수 있습니다. 일반적으로 이러한 요소는 메뉴 항목에서 열립니다. (Google Forms에서는 사용자 인터페이스 요소가 양식을 여는 편집자만 볼 수 있음 응답하기 위해 양식을 여는 사용자가 아니라 수정할 수 있습니다.

알림 대화상자

알림은 Google Docs, Sheets, Slides 또는 Forms 편집기 메시지와 'OK'를 표시합니다. 버튼; 제목 및 대체 버튼은 선택사항입니다. 이것은 window.alert() 를 사용해야 합니다.

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

아래 예에서 볼 수 있듯이 Google Docs, Forms, Slides, Sheets는 모두 Ui.alert() 메서드를 사용합니다. 3가지 변형으로 제공됩니다 기본값인 '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 문서, 스프레드시트, 문서 도구 내에서 열리는 Slides 또는 Forms 편집기 메시지, 텍스트 입력란, 'OK'가 표시됩니다. 버튼; 제목과 대체 버튼은 선택사항입니다. 이것은 window.prompt() 를 사용해야 합니다.

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

아래 예에서 볼 수 있듯이 Google Docs, Forms, Slides, Sheets는 모두 Ui.prompt() 메서드를 사용합니다. 세 가지 변형으로 제공됩니다 기본값인 'OK'를 재정의하는 방법 버튼, Ui.ButtonSet의 값 전달 buttons 인수로 enum을 전달합니다. 사용자의 응답을 평가하려면 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.');
  }
}

맞춤 대화상자

맞춤 대화상자에 HTML 서비스 사용자가 표시될 수 있음 Google Docs, Sheets, Slides 또는 Forms 편집기 내의 인터페이스에 액세스할 수 있습니다

맞춤 대화상자는 대화상자가 열려 있는 동안 서버 측 스크립트를 정지하지 않습니다. 클라이언트 측 구성요소는 서버 측 스크립트를 비동기식으로 호출할 수 있습니다. 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()" />

맞춤 사이드바

사이드바는 HTML 서비스 사용자를 표시할 수 있습니다. Google Docs, Forms, Slides, Sheets 편집기 내의 인터페이스입니다.

사이드바는 대화상자가 열려 있는 동안 서버 측 스크립트를 정지하지 않습니다. 이 클라이언트 측 구성요소가 서버 측 스크립트를 비동기식으로 호출할 수 있음 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 Drive, Google 이미지 검색, Google 비디오를 비롯한 Google 서버 검색 등

아래 예와 같이 Picker의 클라이언트 측 JavaScript API를 사용할 수 있습니다. HTML 서비스에서 맞춤 대화상자를 생성하여 사용자는 기존 파일을 선택하거나 새 파일을 업로드한 다음 선택한 파일을 사용할 수 있습니다.

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

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

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

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

      참고: Google Picker API는 사용 설정하지 않으면 표시되지 않습니다. 목록에 Cloud SQL에 사용 설정된 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>