2
votes

I know similar questions have been asked here before, but I didn't find an answer that helped me. Sorry for that! I'm probably just too inexperienced to understand those answers, so please bear with me.

I have written a Google Apps Script that scans a specific Spreadsheet (not authored by me, but I can view) and counts certain fields. The doGet(e) function returns the count, so when I run the published-as-web-app I see a number.

Now from my background.js in my chrome extension I did something like this:

var my_app = "https://script.google.com/a/macros/google.com/s/.../exec?param=value";
var xhr = new XMLHttpRequest();
try {
  xhr.open("GET", my_app);
  xhr.send(null);
  var result = xhr.getAllResponseHeaders();
  localStorage.count = result;
  chrome.browserAction.setBadgeText({text: localStorage.count});
} catch(e) 
  ...
}

This is very rough, since I'm very new to JavaScript and Chrome Extensions and such.

I'm guessing getAllResponseHeaders() is not how I get to the resulting number that is displayed when calling my_app, so what should I use instead? In the API reference for XMLHttpRequest I didn't find anything obvious.

I'm pretty sure there's a lot more wrong with my code, but let's go one step at a time.

Thanks already in advance! Detailed answers would be great, so I can follow them and extend my currently very limited knowledge.

2
the linked Q solves what you need - Zig Mandel

2 Answers

0
votes

If you are making an HTTP Request from client side JavaScript to Apps Script, then you can use something like this:

function requestToAppsScript() {
  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);

      var theReturnData = xmlhttp.responseText;
      //console.log('return value: ' + theReturnData);

    };
  };

  xmlhttp.open("GET","URL here",true);
  xmlhttp.send();

};
0
votes

basically I just didn't parse the output right. The output I received contained a lot of things and the number I was looking for was hidden in that mess of a string, always behind some string called "cajaHtml".

Therefore the call is now:

xhr.open("GET", my_app);
xhr.onreadystatechange = handleResponse;
xhr.responseType = "text";
xhr.send(null);

with

function handleResponse() {
  if (xhr.readyState == 4) {
    var result = xhr.responseText.split("cajaHtml")[1];
  }
}

Thanks!