Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current instance of "this" file in Google Apps Script?

I'm trying to create a reference to the current DriveApp File object (i.e. the actual Google Drive container for the script itself). Here's what I'm trying to do:

// Assume that thisFile is a FileIterator pointing to THIS file.
// My question in a nutshell: How do I get thisFile?
DriveApp.getFileById( thisFile.getId() );

I want to do this instead of DriveApp.getFileById(id) because I don't want to have to "hard code" the ID string for the script file. That way, if I make a copy of the Google Apps Script project, I don't have to edit anything in the Code.gs or Script Properties. Any suggestions?

like image 410
pumpkin_programmer Avatar asked Jul 18 '14 21:07

pumpkin_programmer


1 Answers

An Apps Script can be standalone or have one of 4 containers (nowadays): Google Sheets, Docs, Forms and Sites. If you know before-hand the type of the container, then it's easy to get its id. e.g.

var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var id = DocumentApp.getActiveDocument().getId();
var id = FormApp.getActiveForm().getId();
var id = SitesApp.getActiveSite().getId();

If you don't know the container type (which would be weird), you could wrap these in various try-catches and find out.

Assuming it's not a Google Site, then you can safely get this id and use it to retrieve the DriveApp File representation of the container.

var file = DriveApp.getFileById(id);

But this file is just an object of the DriveApp API, it's not really a this reference, as in the programming meaning. You could have just as easily used DocsList or advanced Drive service to retrieve a different representation of the same container.

Lastly, I do not know how to grab the id of a standalone script dynamically (from within itself). I suspect it's not possible. But I don't see how that could be useful either. --edit If you want just to copy, why not grab a "fixed" source script directly?

like image 149
Henrique G. Abreu Avatar answered Sep 19 '22 04:09

Henrique G. Abreu