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 to catch up. Sorry for my ignorance. As such, I am really struggling learning Google Apps Script. Obviously, I need to learn JS before I can make sense of any of it.
The school I work for (5000 students) has set up an online curriculum. I created the curriculum in the form of thousands of google document worksheets. These worksheets are linked on various websites.
The problem we are facing is that when students open the documents, they have to make a copy of them before they can edit them (I of course don't want them to be able to edit the originals). This really sucks for students using mobile browsers on their tablets as making a copy in Google Docs doesn't really work well when using the desktop UI on mobile devices.
I know this kind of thing can be automated with script. I've looked here, and low and behold, it works! I'm pissing my pants with joy as I've been searching for such functionality for three years. (Yes, I know that's sad).
So, what I'm asking is, would anyone be willing to help a noob figure out how to adapt this code so that students click a button on a website lesson and it automatically makes and opens a copy of the worksheet in a new tab?
/**
* Copy an existing file.
*
* @param {String} originFileId ID of the origin file to copy.
* @param {String} copyTitle Title of the copy.
*/
function copyFile(originFileId, copyTitle) {
var body = {'title': copyTitle};
var request = gapi.client.drive.files.copy({
'fileId': originFileId,
'resource': body
});
request.execute(function(resp) {
console.log('Copy ID: ' + resp.id);
});
}
Spending all day yesterday learning Javascript, I've still got a long way to go. Not sure how long it'll take for me to be able to figure this out on my own.
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) -
You can test this by putting in your own fileId
.