How to pass non stringifyable objects to html service

If you use sidebars with html service, you are probably used to using google.script.run  to be able to execute apps script functions from within htmlservice, as well as how to pass arguments back and forwards. However, only stringifyable objects can be passed. So for example, you couldn't pass a an Apps Script service - say like a property service. 

While creating Running things in parallel using HTML service, in general I didn't find this to be an issue, but I came across a few examples where I wanted to describe an Apps Script Service, or a library name to use in a profile, which was then passed on to Htmlservice for orchestration, and executed using google.script.run 

These kind of objects get lost in translation because they are non regular JSON type objects.

There is a way round it though. Here's how

Example

Let's say that we want to pass the message that a script to be run by google.script.run should use a particular Property Store. If you take a look at Passing data to html service you'll see how to pass variables to html service. If I wanted to pass something like this

  {
    parameters: {
      "siloid": "polymerdbab",
      "dbid": "xliberation",
      "peanut": "bruce",
      "disablecache":true,
      "driverob": PropertiesService.getScriptProperties()
    }
  }

then driverob would get lost in the process of being passed over to html service, yet here I want to pass information to html service that the apps script will later execute using google.script.run should use. 

So how to do it ?


By including a sub property of eval, and then what needs to be evaled as a string, you can postpone the business of resolving the apps script object until later, inside the context of a script being executed by google.script.run

  {
    parameters: {
      "siloid": "polymerdbab",
      "dbid": "xliberation",
      "peanut": "bruce",
      "disablecache":true,
      "driverob": {
        "eval":"PropertiesService.getScriptProperties();"
       }
    }
  }

The script then just needs to do this to evaluate the parameterized apps script object when it executes. I use the same technique for library names.

  if (opts.driverob && opts.driverob.eval) {
    opts.driverob = eval(opts.driverob.eval);
  } 

Very simple but works great.



For more like this, see  Google Apps Scripts snippets. Why not join our forum,follow the blog or follow me on twitter to ensure you get updates when they are available. 

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.






Comments