Как скрыть боковую панель в электронной таблице Google с помощью скрипта?

Моя таблица имеет боковую панель, как я могу скрыть ее с помощью скрипта?

  SpreadsheetApp.getUi().[method?]

Спасибо за любую помощь!

2 ответа

Не обращайте внимания на то, что я сказал в комментариях к вопросу о явном возврате... синтаксис successHandler сложен. Вам нужно НАИМЕНОВАНИЕ функции, без скобок. Понятия не имею почему, но вы идете.

Code.gs

Вот быстрый пример боковой панели, которая автоматически закрывается после проверки формы ввода. Вы можете проверить поведение ошибки, проигнорировав подсказку.

/**
 * Creates a menu entry in the Google Sheets UI when the document is opened.
 */
function onOpen(e) {
  SpreadsheetApp.getUi().createAddonMenu()
      .addItem('Start', 'showSidebar')
      .addToUi();
}

/**
 * Runs when the add-on is installed.
 */
function onInstall(e) {
  onOpen(e);
}

/**
 * Opens a sidebar in the document containing the add-on's user interface.
 */
function showSidebar() {
  var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
      .setTitle('Simple');
  SpreadsheetApp.getUi().showSidebar(ui);
}


/**
 * Validates the new text, and inserts it into spreadsheet if it is acceptable.
 *
 * @param {string} newText The text with which to replace the current selection.
 */
function insertText(newText) {

  if (newText.indexOf('Pizza') == -1) {
    SpreadsheetApp.getActiveSheet().getActiveCell().setValue(newText);
  }
  else {
    throw new Error( 'No Pizza allowed!' );
  }
  return;
}

Sidebar.html

<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">

<div>
  <form>
    <div>
      <label for="new-text">Enter new text:</label>
      <input type="text" id="new-text" placeholder="Don't enter 'Pizza'!">
    </div>
    <br>
    <div class="block" id="button-bar">
      <button id="insert-text">Insert</button>
    </div>
  </form>
</div>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
  /**
   * On document load, assign click handler
   */
  $(function() {
    $('#insert-text').click(insertText);
  });

  /**
   * Runs a server-side function to validate and enter the entered text.
   */
  function insertText() {
    this.disabled = true;
    $('#error').remove();
    google.script.run
        .withSuccessHandler(google.script.host.close)  // <-- No brackets after function name
        .withFailureHandler(
          function(msg, element) {
            showError(msg, $('#button-bar'));
            element.disabled = false;
          })
        .withUserObject(this)
        .insertText($('#new-text').val());
  }

  /**
   * Inserts a div that contains an error message after a given element.
   *
   * @param msg The error message to display.
   * @param element The element after which to display the error.
   */
  function showError(msg, element) {
    var div = $('<div id="error" class="error">' + msg + '</div>');
    $(element).after(div);
  }
</script>

Вот прямой подход

function closeSidebar() {
    var html = HtmlService.createHtmlOutput("<script>google.script.host.close();</script>");
    SpreadsheetApp.getUi().showSidebar(html);
}

// anywhere on the server-side script (or code.gs)
closeSidebar()

Из документов:

Диалоговое окно может закрыться либо путем вызова google.script.host.close() на клиентской стороне интерфейса HTML-службы, либо UiInstance.close() в интерфейсе UI-службы. Диалог не может быть закрыт другими интерфейсами, только пользователем или самим.

UiInstance.close()устарела. Эта функция устарела и не должна использоваться в новых скриптах

https://developers.google.com/apps-script/guides/dialogs

Другие вопросы по тегам