Search code examples
google-apps-scriptweb-applicationsgoogle-docs

Sidebar button onClick in Google docs script doesn't fire


I'm trying to mechanize calling a docs script routine from a button click (see this question). It seems the only way to do this is to create a sideboard for the document.

Here's my script:

function CreateSideBar ()
{
Logger.log ('CreateSideBar Entry')
var HTML = HtmlService.createHtmlOutput ('<button onClick="CallFromSidebarButton () ;">Do It!</button>').setTitle ('My Sidebar') ;
DocumentApp.getUi ().showSidebar (HTML) ;   
Logger.log ('CreateSideBar Exit')
}

function onOpen() 
{
CreateSideBar ()  
}


function CallFromSidebarButton ()
{
var ui = DocumentApp.getUi () ; 
ui.alert ('Call from sidebar OK') ;  
}

Things work fine if I call them from the script debugger, but if I open the document, the sidebar creates OK, but nothing happens when I click on the button.

Inspection shows:

userCodeAppPanel:1 Uncaught ReferenceError: CallFromSidebarButton is not defined
    at HTMLButtonElement.onclick (userCodeAppPanel:1)

The doc is shared here. You will probably need to be signed in and agree to a bunch of stuff.


Solution

  • To call a server side function from client side code you have to use google.script.run i.e. replace

    var HTML = HtmlService.createHtmlOutput ('<button onClick="CallFromSidebarButton () ;">Do It!</button>').setTitle ('My Sidebar') ;
    

    by

    var HTML = HtmlService.createHtmlOutput ('<button onClick="google.script.run.CallFromSidebarButton () ;">Do It!</button>').setTitle ('My Sidebar') ;
    

    Resources

    Related