Add a Document Sidebar with Google Apps Script

In this older post I showed you how to use the onOpen() trigger to add a menu item in the old Google Sheets. The interface is a little different in Forms, Docs and the new Google Sheets, so here we’ll look at the new syntax. We’ll then extend this functionality a little by creating a sidebar for a document.

This was how things worked in the old Sheets:

function onOpen() { 
 var sheet = SpreadsheetApp.getActiveSpreadsheet(); 
 var items = [{name:'Show dialog', functionName:'showDialog'}]; 
 sheet.addMenu('Custom Menu', items);
}

In Forms, Docs and the new version of Sheets we instead use the getUi() method of the SpreadsheetApp object (or DocumentApp, FormApp as required) to create and later display the new menu.

Here’s example code for a Document:

function onOpen() {
 DocumentApp.getUi()
     .createMenu('Sidebar').addItem('Open', 'openSidebar').addToUi();
}

For the code to do anything, and not throw an error, we also need to define the custom function openSidebar(). We’ll use this to open a sidebar on the document containing our own custom HTML code.

Start by creating a new file index.html in the code editor, and putting in the required HTML. (Note that you need to create this in the code editor, not via some external application that then stores it in Drive).

Here I’ve kept the HTML file very simple:

<div>
Welcome to my sidebar!<br/>
<input type="button" value="Close Sidebar" onclick="google.script.host.close()" />
</div>

Now, back in our App Script, we’ll define the openSidebar() function to display this HTML markup using the HtmlService object:

function openSidebar() {
 var html = HtmlService.createHtmlOutputFromFile('index');
 DocumentApp.getUi().showSidebar(html);
}

Here’s the Apps Script code in the Code Editor:

Click image to enlarge

Click image to enlarge

 And the HTML page for the sidebar:

Click image to enlarge

Click image to enlarge

Now, when the document is opened, a new menu item ‘Sidebar’ is created with a submenu item ‘Open’.

Click image to enlarge

Click image to enlarge

Selecting ‘Open’ pops open the sidebar. In this case, all that’s contained in our HTML is a simple message and a button to close the sidebar:

Click image to enlarge

Click image to enlarge