skip to Main Content

I am starting from javascript in google scripts (apps scripts) bounded to a sheet.
I succesfully open html in a sidebar.
Also I add an argument I want to use later, to formTemplate object.

//OPEN THE FORM IN SIDEBAR with argument passed to formTemplate
function showFormInSidebar(argument ='I want pass this') { 
  let htmlName = 'Index'
  var htmlTemplate = HtmlService.createTemplateFromFile(htmlName)
  htmlTemplate.argument = argument;
  var html = htmlTemplate.evaluate();  
  SpreadsheetApp.getUi().showSidebar(html);
}

Next, I use Index.html.
I can read there my argument with some google scripts stuff, test1 is ok.

Then I check I can see an action from my secondary javascript function – test2. I can run it with click (or on ‘load’ event). This works fine.

And the main question is how to obtain my argument value inside a secondary JS?
Direct arg pass not working. Argument inside secondaryJS is anyway only an event object. There is a huge amount of data there, but my initial argument I cannot find.

<!DOCTYPE html>
<html>
  <head>
    <script>
      window.addEventListener('click', secondaryJS); 
      function secondaryJS(event){                 
        console.log('look event', event);
        document.getElementById("mytest2").innerHTML = 'This is replacing ok'
        document.getElementById("mytest3").innerHTML = '???? want pass initial argument here, inside this function'
      }
    </script>
  </head>

  <body>
    <p>test1, reading argument from htmlTemplate.argument, ok:</p>
    <p><?!= argument ?></p>

    <p>test2:</p>    
    <p id = "mytest2">Must be replaced from secondaryJS with string value after page load, ok</p>

    <p>test3:</p>
    <p id = "mytest3">Must be replaced from secondaryJS with argument passed from event listener function, NOTok</p>    
  </body>
</html>

2

Answers


  1. Change:

    <p><?!= argument ?></p>
    
    document.getElementById("mytest3").innerHTML = '???? want pass initial argument here'
    

    To this:

    <p id = "mytest1"><?!= argument ?></p>
    
    document.getElementById("mytest3").innerHTML = document.getElementById("mytest1").innerHTML;
    
    Login or Signup to reply.
  2. Try this:

    GAS:

    function showFormInSidebar(b ='I want pass this') { 
      var t = HtmlService.createTemplateFromFile('ah2');//My file is named "ah2.html"
      t.a = b;
      var html = t.evaluate();  
      SpreadsheetApp.getUi().showSidebar(html);
    }
    

    html:

    <!DOCTYPE html>
    <html>
      <head>
      </head>
      <body>
        <p>test1, reading argument from htmlTemplate.argument, ok:</p>
        <p><?= a ?></p>
      </body>
    </html>
    

    Sidebar:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search