[GAS Beginner Series #50] Grant Google Drive View Access Automatically: How to Use File.addViewer() and Manage Permissions

Have you ever been asked to handle file permissions for an upcoming project or event, like “Could you give everyone view access to this document?” or “Please grant read permissions for this PDF to all study group attendees”?

Manually opening Google Drive, clicking the “Share” button, typing each email address one by one, switching permissions to “Viewer,” and sending notifications… If it is just two or three people, it is manageable. But once the list grows to dozens of attendees, it turns into a massive time sink! On top of that, manual entry always brings the risk of typos and accidental edit permissions.

That is where Google Apps Script (GAS) comes to the rescue with File.addViewer(), letting you automate Google Drive file permission management in just a few lines of code!

In this guide, we will use shared materials for the “Sapporo IT Engineer Study Group” as our real-world project to learn how to grant view access to colleagues and participants automatically in bulk. This milestone 50th lesson marks the grand finale of Phase 5 (Google Drive & File Management), so let’s master it together!

1. What Is File.addViewer()?

File.addViewer() is a Google Apps Script method called on a specific file (File object) in Google Drive to grant “Viewer” access to a designated user (email address).

Basic Code Structure

// 1. Retrieve the file (grab the target file from Drive)
var file = DriveApp.getFileById("FILE_ID");

// 2. Grant view access to the specified email address
file.addViewer("member@example.com");

Google Drive’s 3 Access Roles vs. GAS Methods

Google Drive allows granular access control per user. GAS provides dedicated methods mapped to each access level.

Access Role Drive UI Label Allowed Actions Single-User Method Multi-User (Array) Method
Viewer Viewer View and download only (no editing) File.addViewer() ★Today’s topic! File.addViewers()
Commenter Commenter View files and leave comments File.addCommenter() File.addCommenters()
Editor Editor Edit, delete, and modify sharing permissions File.addEditor() File.addEditors()

When you want to share slides or handouts without risking someone accidentally editing or deleting your content, File.addViewer() is the safest, most reliable choice.

2. Step 1: Preparation! Create the “Sapporo Engineer Study Group Materials”

First, let’s prepare a test file in Google Drive and grab its unique File ID.

Steps

  1. Open Google Drive
    Navigate to your Google Drive account.
  2. Prepare a Test File
    Create or upload a file (e.g., a Google Doc, Google Slides deck, or PDF) in Drive, and rename it to “Sapporo Engineer Study Group Materials”.
  3. Copy the File ID
    Open the file and copy the unique File ID (a long string of random alphanumeric characters) from the browser URL bar.
    • Example: In https://docs.google.com/document/d/1a2b3c4d5e6f7g8h9i0j_EXAMPLE_ID/edit, the 1a2b3c4d5e6f7g8h9i0j_EXAMPLE_ID portion is your File ID.

3. Step 2: Hands-on! Grant View Access to a Single User

Now that your file is ready, open the GAS script editor and write your first permission script.

1. Enter the Code

Open your spreadsheet or standalone Apps Script editor (Extensions > Apps Script) and paste the code below. Replace the File ID and email address with values matching your test setup.

function addSingleViewer() {
  // 1. Specify the target file ID
  var fileId = "PASTE_YOUR_FILE_ID_HERE"; // Replace with your actual file ID
  
  // 2. Retrieve the file object (the familiar method from Lessons #41-#44!)
  var file = DriveApp.getFileById(fileId);
  
  // 3. Specify the colleague's email address
  var userEmail = "sapporo.member@example.com"; // Real account or secondary test address
  
  // 4. Grant Viewer access
  file.addViewer(userEmail);
  
  // 5. Output log to verify completion
  Logger.log("Granted Viewer access for " + userEmail + " to file: \"" + file.getName() + "\"!");
}

2. Code Walkthrough

  • DriveApp.getFileById(fileId)
    As introduced in Lessons #44 and #49, this method searches Google Drive using the provided ID string and returns the corresponding File object.
  • file.addViewer(userEmail)
    Calls .addViewer() on the file instance, passing the user’s email address as a string argument. Google Drive immediately updates its access control list and grants view permissions to that user.

3. Run and Verify

  1. Click the “Save” (floppy disk icon) button in the toolbar.
  2. Select the addSingleViewer function and click “Run”. *If this is your first run, an authorization dialog will ask for Drive access permissions. Grant access by following the on-screen prompts (as covered in Lesson #2).
  3. Open the “Share” modal for your file in Google Drive. If the email address appears as a “Viewer”, congratulations—it worked!

4. Step 3: Practical Workflow! Bulk Share from a Spreadsheet Roster

In production workflows and community management, you will almost always want to “automatically grant view access to everyone registered on a Google Sheets participant list.”

By combining Range.getValues() and array iteration from Lesson #7, let’s build a real-world script that loops through spreadsheet email addresses and runs addViewer() in bulk!

1. Set Up the Practice Spreadsheet

Create a sheet named “Participant List” in your spreadsheet and populate it with sample attendee data:

A B C
1 Name Role/Affiliation Email Address
2 Taro Sapporo Engineer taro@example.com
3 Hanako Odori Designer hanako@example.com
4 Jiro Susukino Director jiro@example.com

2. Bulk Sharing Script

function addViewersFromSheet() {
  // 1. Get study material File ID and target spreadsheet
  var fileId = "PASTE_YOUR_FILE_ID_HERE";
  var file = DriveApp.getFileById(fileId);
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Participant List");
  
  // 2. Identify the last populated row (getLastRow from Lesson #11)
  var lastRow = sheet.getLastRow();
  if (lastRow < 2) {
    Logger.log("No target data found in sheet.");
    return;
  }
  
  // 3. Batch retrieve email addresses from cell C2 to the last row (Lesson #13 getValues)
  // getRange(startRow, startColumn, numRows, numColumns)
  var emailValues = sheet.getRange(2, 3, lastRow - 1, 1).getValues();
  
  // 4. Iterate through email addresses and assign access
  var addedCount = 0;
  for (var i = 0; i < emailValues.length; i++) {
    var email = emailValues[i][0];
    
    // Verify cell is not empty
    if (email !== "") {
      file.addViewer(email);
      Logger.log("User #" + (i + 1) + ": Granted Viewer access to " + email);
      addedCount++;
    }
  }
  
  Logger.log("[Complete] Successfully granted Viewer access to " + addedCount + " users for \"" + file.getName() + "\"!");
}

💡 Pro Tip: Optimize with the Plural addViewers() Method

Instead of calling addViewer() one by one inside a loop, Google Apps Script provides File.addViewers() (ending with an s), which accepts a 1D array of email addresses all at once.

// Passing an array of email addresses in a single call
var emailList = ["taro@example.com", "hanako@example.com", "jiro@example.com"];
file.addViewers(emailList);

When sharing with dozens or hundreds of users, addViewers() significantly cuts down network roundtrips, speeds up execution time, and keeps your code elegant!

5. 4 Common Pitfalls for Beginners and How to Fix Them

Here are four frequent traps beginners fall into when working with File.addViewer(), along with their solutions.

Pitfall 1: Confusing addViewer (Singular) with addViewers (Plural)

  • Singular addViewer("email"): Accepts a string (a single email address).
  • Plural addViewers(["email1", "email2"]): Accepts an array (a list of email strings).

Passing an array into the singular method like addViewer(["email1", "email2"]) will cause a type error or silently fail. Make sure your argument data type matches the method signature.

Pitfall 2: Insufficient Account Permissions on the File

To alter file sharing settings, the account executing the script must be either the File Owner or an Editor with permission to change sharing options.

Attempting to modify permissions on a file where you only have Viewer rights will trigger an Exception: You do not have permission to call DriveApp.getFileById... or an access denied error. Ensure the authorized account has edit-level ownership before running.

Pitfall 3: Typographical Errors and External Domain Sharing Policies

  • A typo in the email address prevents Google Drive from resolving the user.
  • If you are working within a corporate Google Workspace tenant, workspace administrators frequently restrict file sharing outside the organization’s domain. Adding external domains (like personal @gmail.com accounts) will fail under these security restrictions.

Pitfall 4: Automatic Invitation Email Notifications

By default in Google Drive, calling addViewer() can automatically trigger an email notification to the recipient announcing that a document has been shared with them.

When conducting local development or testing, using actual coworker addresses might send unexpected notification emails. Always test using personal test accounts or pre-notified staging addresses first.

6. Phase 5 Complete! Google Drive & File Management Recap

Started back in Lesson #41, our “Phase 5: Google Drive & File Management” series is now officially complete with this 50th lesson!

Let’s review the essential Google Drive automation methods you have mastered throughout Phase 5:

  • Lesson #41: Locate folders via DriveApp.getFolderById()
  • Lesson #42: Generate new files with Folder.createFile()
  • Lesson #43: Enumerate folder items using Folder.getFiles()
  • Lesson #44: Duplicate templates with File.makeCopy()
  • Lesson #45: Dynamically rename files using File.setName()
  • Lesson #46: Relocate files into target folders with File.moveTo()
  • Lesson #47: Clean up unwanted files via File.setTrashed()
  • Lesson #48: Dynamically create folder structures with DriveApp.createFolder()
  • Lesson #49: Generate direct download endpoints using File.getDownloadUrl()
  • Lesson #50: Automate Viewer permission sharing with File.addViewer() ★Today’s achievement!

Beyond simple spreadsheet calculations and Gmail automation, you now possess full programmatic control to create, organize, archive, and manage access permissions across Google Drive!

Starting next lesson, we enter Phase 6: Google Docs, Slides & Forms Integration (Lessons #51 through #60)! See you there!