2

I have a google apps script function that is pulling data from a spreadsheet. It is able to log the information happily and then I return the data to a javascript function. But when I try to stringify and alert the information it alerts "null".

Not sure where I am going wrong!

Javascript calling the GAS function:

google.script.run.withSuccessHandler(getNews).getTheNews();

GAS function:

function getTheNews(){

 var ss = SpreadsheetApp.openByUrl(url);
 var ws = ss.getSheetByName("NewsFeed"); 
  
 
  var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
  Logger.log(theNews);
  
 return theNews;
 
}

The GAS log: enter image description here

Javascript function receiving the info:

function getNews(theNews){
var mystr = JSON.stringify(theNews);
            alert(mystr);
}

1 Answer 1

2

Issue and workaround:

Unfortunately, it seems that in the current stage, the date object cannot be directly returned from Google Apps Script side to Javascript side. Also I could replicate your situation. I think that this is the reason of your issue. So as the current workaround, how about the following modification?

Modified script:

In this modification, the date object is converted to the string and sent to Javascript side. At Javascript side, the date string is converted to the date object.

HTML & Javascript side:

google.script.run.withSuccessHandler(getNews).getTheNews();

function getNews(theNews){
  theNews = theNews.map(r => r.map(c => new Date(c)));  // Added
  var mystr = JSON.stringify(theNews);
  alert(mystr);
}

Google Apps Script side:

function getTheNews(){
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("NewsFeed");
  var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
  return theNews.map(r => r.map(c => c.toISOString()));  // Modified
}
  • I think that in this case, c.getTime() instead of c.toISOString() can be also used.

Note:

  • For example, if you want to retrieve the display values on the cells, you can also modify as follows. In this case, Javascript is not required to be modified.

    • From

        var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
      
    • To

        var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getDisplayValues();
      
  • Also I found this issue at the Google issue tracker. Ref But when I saw the status, it seems "Won't Fix (Intended behavior)".

References:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.