简体   繁体   中英

google.script.run independent usage

Now that the client side of a Google Apps Script is standalone with HtmlService, I want the option to develop it independently of the client side (mainly to get the benefits of normal editor, js & css files and not be bothered by sandboxing). This can mean implementing my own doGet/doPost on the server side script, but then I loose the nicety of using google.script.run to directly call functions and accept results.

So, is there a way to use google.script.run independently? 

You can do something like call a Google Apps Script Content Service from an AJAX request in a website and get a return value.

Google Documentation - Content Service

That doesn't use the google.script.run API, but it's basically the same thing. If what you want is to run Apps Script server side code without displaying anything to the user, then you can do that with a JavaScript (jQuery, etc) AJAX call to the Apps Script Content Service apps URL.

Suppose you have a JavaScript function named "runAjaxToGetNames". And it's called with the following line:

runAjaxToGetNames("https://script.google.com/macros/s/AKfycbyFyODk/exec");

An argument is passed that is the URL of the Apps Script Stand Alone Content Service app.

The AJAX function looks like this:

function runAjaxToGetNames(argURL_forAJAX) {

  console.log('runAjaxToGetNames ran: ' + argURL_forAJAX);

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    //console.log'xmlhttp.readyState: ' + xmlhttp.readyState);
    if (xmlhttp.readyState===4 && xmlhttp.status===200) {
      //console.log'xmlhttp.responseText: ' + xmlhttp.responseText);

      glblStoreNames.names = xmlhttp.responseText;
      //console.log'return value into the global object?: ' + glblStoreNames.names);
      //Call a function to populate the store names
      populateStoreNames();

    };
  };

  xmlhttp.open("GET",argURL_forAJAX,true);
  xmlhttp.send();
};

The Apps Script content service is a file all to itself with only the following code:

//This Apps Script is to get a list of all the names out of a Google Doc.
function doGet() {
  var theGogDocReference = DocsList.getFileById('YWY4ZmM5OQ_File_ID_Here');
  var theContent = theGogDocReference.getContentAsString();
  return ContentService.createTextOutput(theContent);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM