Dr Adam Stanton

Researcher in Adaptive Informatics

How to use gscript to choose a random file from a Google Drive folder, and open it?

It’s not so hard, though the gscript has to be published as a web app. Write the doGet function to retrieve the URL of the file in Drive, then return a small script that redirects to the URL using HtmlService.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
function doGet(e) {
  var folder = DriveApp.getFolderById("your-folder-id");
  var files = folder.getFiles();
 
  var filearray = new Array;
  var c=0;
 
  while(files.hasNext()) {
    var s = files.next();
    filearray[c] = s.getUrl();
    c=c+1;
  }
 
  var item = Math.round( Math.random() * filearray.length );
  var itemurl = filearray[item];

  var html="<script>window.top.location.href='"+itemurl+"';</script>";
 
  return HtmlService.createHtmlOutput(html);
}

Comments are closed.