Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created January 9, 2019 02:57
Show Gist options
  • Save tanaikech/c1b5fb20342dae623139ca0f48c8c12c to your computer and use it in GitHub Desktop.
Save tanaikech/c1b5fb20342dae623139ca0f48c8c12c to your computer and use it in GitHub Desktop.
Closing Existing Sidebar using Google Apps Script

Closing Existing Sidebar using Google Apps Script

This is a sample script for closing the existing sidebar using Google Apps Script. When the sidebar is opened, in order to close the sidebar, the sidebar can be closed by running google.script.host.close() with the script of sidebar. This is the general case.

If you want to close the opened sidebar, such functions are not prepared. So I thought this workaround. The flow of this workaround is as follows.

Flow:

  1. Open a sidebar. Run run1_openSidebar().
    • At this time, an object {"sidebar": "open"} is put using PropertiesService.
  2. Close the sidebar. Run run2_closeSidebar().
    • When sidebar is open, this script is run.
    • In this case, the existing sidebar is overwritten by a temporal sidebar. 2 sidebars cannot be opened, simultaneously. This is the important point. By this, the sidebar can be closed by GAS.

Sample script:

In this script, the container-bound script of Spreadsheet is used as a sample.

function run1_openSidebar() {
  var p = PropertiesService.getScriptProperties();
  p.setProperty("sidebar", "open");
  var html = HtmlService.createHtmlOutput("sample sidebar");
  SpreadsheetApp.getUi().showSidebar(html);
}

function run2_closeSidebar() {
  var p = PropertiesService.getScriptProperties();
  if (p.getProperty("sidebar") == "open") {
    var html = HtmlService.createHtmlOutput("<script>google.script.host.close();</script>");
    SpreadsheetApp.getUi().showSidebar(html);
    p.setProperty("sidebar", "close");
  }
}

Note:

  • This sample script uses Spreadsheet. So if you want to use other Google Docs, please modify it.
  • This method can be also used for the custom dialog.
  • This workaround was answered at https://stackoverflow.com/a/54082847.

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment