Search code examples
htmlgoogle-apps-scriptgoogle-sitesdrive

Display a list of all Google Drive files on Google site


I am trying to display this as a web app. It only returns 1 file on the site. The logs show 50+ files. Why doesn't htmloutput show all the files like the logs do. Any help would be awesome.

function doGet(e) {
  var query = 'fullText contains "Printers"' ;
  var folders, pageToken;
  do {
    folders = Drive.Files.list({
      q: query,
      maxResults: 100,
      pageToken: pageToken
    });

    if (folders.items && folders.items.length > 0) {
      for (var i = 0; i < folders.items.length; i++) {
        var folder = folders.items[i];

        Logger.log('%s (ID: %s)', folder.title, folder.id);
      }
    } else {
    }
    var Output3 = folder.id; 
    var output = HtmlService.createHtmlOutput(Output3);
    pageToken = folders.nextPageToken;
  } while (pageToken);

  return output
}

Solution

  • Every time your for loop iterates, it's overwriting the previous contents.

    var Output3 = folder.id;
    

    You would need to use something like:

    var Output3 = "";//define this outside the `for` loop
    Output3 = Output3 + folder.id;
    

    Here is a rework of your full code:

    function doGet() {
      var query = 'fullText contains "Printers"' ;
      var folders, folder, pageToken, foldersLngth = 0, theItems, output="";
    
      do {
        folders = Drive.Files.list({
        q: query,
        maxResults: 100,
        pageToken: pageToken
      });
    
      foldersLngth = folders.items.length;
      theItems = folders.items;
    
      if (theItems && foldersLngth > 0) {
    
        for (var i=0; i < foldersLngth; i++) {
          folder = folders.items[i];
          Logger.log('%s (ID: %s)', folder.title, folder.id);
          output = output + folder.title + ", " + folder.id;
        };
      };
    
      //var Output3 = folder.id; 
      //HtmlService.createHtmlOutput(Output3);
      pageToken = folders.nextPageToken;
      } while (pageToken);
    
      return HtmlService.createHtmlOutput(output);
    };