Google Apps Script: sharing your documents with ‘Viewers’
When working with google docs the best results come with collaborating with other people. These groups of people can be your family members that you are sharing with or like me with your work teammates. No one lives or works in a vacuum, and the sharing feature to allow others to view or help edit your work is one of the leading features that google docs provides.
Whether your group of viewers and editors is small or large, it is a lot faster to utilize google apps script to help you manage your viewer/editor list. As your work complexity and your user list changes it is easy to add and remove viewers/editors from your google documents. In this blog we will start with adding and removing Viewers. We will cover adding and removing Editors in the next blog.
We will begin with a simple task of allowing others access to your document by adding a viewer by calling a function ‘addViewers()’. And we will follow up with an opposite functionality to remove a single user with ‘removeViewer()’. When we add a viewer to a spreadsheet and the user was already on the list of editors, the method ‘addViewers’ has no effect. Another issue to keep in mind is that we can add multiple Viewers with a single function call and passing an array of emails. But to remove a viewer you can only do one email at a time.
Let's start with a simple function that will create a list of emails. Make sure you add valid emails otherwise google script will generate an error if the email address is invalid. You can use another Spreadsheet as your data source to keep your list of emails and populate an array with this information.
function crtViewerList() {
var emailList = [];
emailList.push("valid-email-01@gmail.com");
emailList.push("valid-email-02@gmail.com");
return(emailList);
};
Once your list is built you can call a single function to add these emails to your google document viewer list.
sSheet.addViewers(emailList);
To remove a single viewer from your viewers list you would call ‘removeViewer()’, function but this time only with a single email.
sSheet.removeViewer(emailAddr);
The rest of the code is pretty straightforward and will depend on how you would like to manage your viewer list access. Putting it all together, the full code:
function delViewerFromSsheet(emailAddr, sSheet) {
sSheet.removeViewer(emailAddr);
};
function addViewerListToSsheet(emailList, sSheet) {
sSheet.addViewers(emailList);
};
function crtViewerList() {
var emailList = [];
emailList.push("valid-email-01@gmail.com");
emailList.push("valid-email-02@gmail.com");
return(emailList);
};
function myMainShareWithViewers() {
const sSheet = SpreadsheetApp.getActiveSpreadsheet();
var emailList = crtViewerList();
addViewerListToSsheet(emailList, sSheet);
Logger.log(sSheet.getViewers());
delViewerFromSsheet("valid-email-01@gmail.com", sSheet);
delViewerFromSsheet("valid-email-02@gmail.com", sSheet);
Logger.log(sSheet.getViewers());
};