Search code examples
htmlgoogle-apps-scriptgoogle-sheetssidebar

HTML (sidebar) calling library scripts, possible?


I've created a sidebar in HTML on Spreadsheets, and all worked perfectly, but when moved to the library where all code is maintained, it stopped working, the function utilized by the sidebar is now undefined, how can I call the function in the library "FuncoesOrcamentoV2" directly from the sidebar? It's impractical to copy the code to every Spreadsheet, there's dozens of them.

Example:

form.html

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" /> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>

<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete" disabled="true" value="Carregando..." clss="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content">
<input type="button" value="Close" onclick="escrever()" />
<script>
function autoCompletar( comps ){
$( "#autocomplete" ).removeAttr("disabled").removeAttr("value");
    $( "#autocomplete" ).autocomplete({
    source: comps
    });
}
google.script.run.withSuccessHandler( autoCompletar ).arrayObjetos(); //arrayObjetos cannot be called
</script>

code.gs -> in the library FuncoesOrcamentoV2

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');
}

function arrayObjetos(){
var composicoes = FuncoesOrcamentoV2.composicoesObject( ),
     arrayFinal = [];

  for( comp in composicoes )
    arrayFinal.push( comp );

  return arrayFinal;
}

Solution

  • Not the most elegant way, but using a form of eval() works for my case:

    code.gs on every sheet:

    function funcoesOrcamento( funcao, args ){
      if(args)
        args = args.split("\!|");
      else
        args = [];
    
      return FuncoesOrcamentoV2[ funcao ].apply(this, args);
    }
    

    and on the HTML sidebar:

    google.script.run.withSuccessHandler( salvaNivelColuna ).funcoesOrcamento( "nivelColuna" );
    google.script.run.withSuccessHandler( autoCompletar ).funcoesOrcamento( "arrayObjetos" );