Search code examples
google-apps-scriptgoogle-sheets

Is there a way to silently share a file when a cell is changed in g-sheets?


I have several hundred links to other sheets in a column, a checkbox column, and an email column. I'd like to share the sheet with the email when the checkbox is checked within each row. I can share the sheets with a function, but the code won't share when I run it onEdit(e).

I think it's the LIMITED mode of onEdit(e) that won't allow it to share a file.

Is there another way to trigger my file sharing function when one of the checkboxes is checked or unchecked?

Or, is there a way to trigger a custom function using conditional formatting? Or will that still run LIMITED?

This pulls id from url:

`function getIdFromUrl(url) { return url.match(/[-\w]{25,}(?!.*[-\w]{25,})/); }`

This is what I am using for sharing:

`function silentShare(fileId, email){
  try {
       Drive.Permissions.insert(
         {
           'role': 'writer',
           'type': 'user',
           'value': email
         },
         fileId,
         {
           'sendNotificationEmails': 'false'
         });
       return true; //if it works return true
     } catch (e) {
  
       return false; //if it returns false, no luck
     }
 }`

Solution

  • Explanation:

    Unfortunately this is a limitation of the onEdit function. This is stated in the documentation in this link in the Restriction Section: https://developers.google.com/apps-script/guides/triggers

    They cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization, but a simple trigger can translate a phrase with the Language service, which is anonymous.

    Sharing file from a drive requires authorization.

    https://developers.google.com/apps-script/guides/services/authorization


    Suggestion:

    As mentioned by Tanaike in the comment you will have to install the trigger for EDIT. Installable triggers can call services that require authorization.

    Refer to this documentation: Managing Triggers Manually

    To manually install onEdit trigger go to the Triggers menu from the Apps Script: enter image description here

    Then -> Add Trigger

    Select the function you want to run when edited, then Event type should be On edit. enter image description here