I feel like a total noob posting here. I know CSS, HTML, and XML pretty well but have always avoided JS. I know very little javascript and recently started a Lynda.com course
Here is the code to do it properly (works in 2019,2020,2021):
/**
* Create custom menu when document is opened.
*/
function onOpen() {
DocumentApp.getUi()
.createMenu('For Students')
.addItem('Make a copy', 'makeACopy')
.addToUi();
}
function makeACopy() {
var templateId = DocumentApp.getActiveDocument().getId();
DriveApp.getFileById(templateId).makeCopy();
}
You can certainly do this with Apps Script. Only takes a couple of lines. In fact, you can use just the version I wrote below.
Here is how I would do it -
Ensure you original document is at least read enabled for the folks that will be accessing it.
Grab the fileId from the URL -
Write a web app in Apps Script with the following code -
function doGet(e) {
//file has to be at least readable by the person running the script
var fileId = e.parameters.fileId;
if(!fileId){
//have a default fileId for testing.
fileId = '1K7OA1lnzphJRuJ7ZjCfLu83MSwOXoEKWY6BuqYitTQQ';
}
var newUrl = DocsList.getFileById(fileId).makeCopy('File copied to my drive').getUrl();
return HtmlService.createHtmlOutput('<h1><a href="'+newUrl+'">Open Document</a></h1>');
}
Deploy it to run as the person accessing the app.
One key thing to remember is that a web app built by Apps Script cannot force open a new window automatically. Instead we can show a link which is clickable into the document in edit mode.
You can see it in action here (will create some dummy file) -
https://script.google.com/macros/s/AKfycbyvxkYqgPQEb3ICieywqWrQ2-2KWb-V0MghR2xayQyExFgVT2h3/exec?fileId=0AkJNj_IM2wiPdGhsNEJzZ2RtZU9NaHc4QXdvbHhSM0E
You can test this by putting in your own fileId
.
Update as of 2015, Google Script removed the fileId for reasons unknown. The previous method of appending "/copy" to the URL of the Google doc has been re-enabled. Ex) https://docs.google.com/document/d/1GTGuLqahAKS3ptjrfLSYCjKz4FBecv4dITPuKfdnrmY/copy
Since DocsList
is deprecated, currently you can make a copy of a file using the following code:
File file=DriveApp.getFileById(fileId).makeCopy(fileName, folder);
where fileId
can be obtained as explained in the answer by Arun Nagarajan.