Home > OS >  getViewers returns always an empty array
getViewers returns always an empty array

Time:09-04

Dears, I'm asking for your help regarding the getViewers method in Google Drive.

This is the sample code:

function test_getViewers() {
  var gmail_address = "[email protected]"
  var foto_folder_id = "my folder id"    // real id has been removed    
  //Read the users and add the gmail address only if it is NOT present as viewer
  var foto_folder_viewers = DriveApp.getFolderById(foto_folder_id).getViewers();
  //Add the gmail user as viewer
  if(foto_folder_viewers.indexOf(gmail_address<0)){
    DriveApp.getFolderById(foto_folder_id).addViewer(gmail_address);    
  } 
}

Unfortunately the foto_folder_viewers is always an empty array.

Thank you, Nicola

CodePudding user response:

getViewers returns array of User objects:

function test_getViewers() {
  var gmail_address = "[email protected]"
  var foto_folder_id = "";    // real id has been removed    
  //Read the users and add the gmail address only if it is NOT present as viewer
  var folder = DriveApp.getFolderById(foto_folder_id);
  
  //Add the gmail user as viewer
  if(!isViewer(folder, gmail_address)){
    folder.addViewer(gmail_address);    
  } 
}

function isViewer(folder, email)
{
  var viewers = folder.getViewers();

  return viewers.findIndex(user => user.getEmail() === email) !== -1;
}

CodePudding user response:

If I've understood your problem correctly you have a list of known addresses that you want to add to a specific folder as viewers, but first you want to check if they already have this permission.

Re-adding a person as a viewer shouldn't really be a problem, but even if it was, you could do the following:

function addUsersIfNotViewers() {
  const gmailAddresses = ["[email protected]", "[email protected]"];

  const folderId = "your-secret-folder-id";
  const folder = DriveApp.getFolderById(folderId);
  const folderViewers = folder.getViewers();
  console.log(folderViewers);  // This should return a User[]
  
  const addressesNotViewingFolder = gmailAddresses.filter((address) => !folderViewers.includes(address));
  folder.addViewers(addressesNotViewingFolder);
}

One reason your folder.getViewers() returns [] might be not having enough permissions on the folder. The documentation says:

Gets the list of viewers and commenters for this Folder. If the user who executes the script does not have edit access to the Folder, this method returns an empty array.

Ensure you have enough permissions, then try again with the above snippet. Enjoy!

  • Related