Code Guy
Code Guy

Reputation: 3198

making gs file as both an apps script file as client js file

I have a custom file which can serve for both server side a.gs as well as cleint side a.js, both has same functions defined

instead of having a.gs and a.js how will I make

function include(filename) {
    return HtmlService.createHtmlOutputFromFile('<script>'+a.gs+'</script>').getContent();
}

something like above.

Upvotes: 0

Views: 278

Answers (1)

Tesseract
Tesseract

Reputation: 8139

In your doGet function you can check if a specific parameter is present and then send all or part of the code contained in a.gs to the client.

function doGet(e) {
  if(e.parameter.func) {
    var out = ContentService.createTextOutput(this[e.parameter.func].toString());
    out.setMimeType(ContentService.MimeType.JAVASCRIPT);
    return out;
  }
}

Now you can add this line to your html file <script type="text/javascript" src="https://script.google.com/macros/s/<id>/exec?func=myFunction"></script> in order to use myFunction on the client.

But if you want to make everything in a.gs available to the client and not just a single function you could do this

function genCode2(obj) {
  if(obj instanceof Array) return JSON.stringify(obj);
  if(obj === null) return "null";
  if(typeof(obj) === "undefined") return "undefined";
  if(typeof(obj) === "object") {
    var str = "{\n";
    for(key in obj) {
      if(typeof obj[key] === "function") {
        var s = obj[key].toString() + "\n";
        if(s.indexOf("[native code") < 0) str += "\"" + key + "\": " + s + ",\n";
      } else {
        str += "\"" + key + "\": " + genCode2(obj[key]) + ",\n";
      }
    }
    return str + "\n}";
  }
  return JSON.stringify(obj);
}

function genCode(obj) {
  var str = "";
  for(key in obj) {
    if(typeof obj[key] === "function") {
      var s = obj[key].toString() + "\n";
      if(s.indexOf("[native code") < 0) str += s;
    } else {
      str += "var " + key + " = " + genCode2(obj[key]) + ";\n";
    }
  }
  return str + "";
}

function doGet(e) {
  if(e.parameter.file === "a.gs") {
    var out = ContentService.createTextOutput(genCode(this));
    out.setMimeType(ContentService.MimeType.JAVASCRIPT);
    return out;
  }
}

And then put <script type="text/javascript" src="https://script.google.com/macros/s/<id>/exec?file=a.gs"></script> in the html file.

But on the other hand, maybe you could just put a js file into your google drive which you could then load in a.gs and send to the client or evaluate with eval.

Upvotes: 2

Related Questions