Transferring Owner of File to Other User using Google Apps Script

Gists

Transferring Owner of File to Other User using Google Apps Script

This is a sample script for transferring the ownership of a file to another user using Google Apps Script.

In the current stage, about the consumer account (gmail.com) the specification for transferring the ownership of a file has been changed as follows. Ref

  1. The current owner initiates an ownership transfer by creating or updating the prospective new owner’s file permission. The permission must include these settings: role=writer, type=user, and pendingOwner=true. If the new owner is creating a permission for the prospective owner, an email notification is sent to the prospective new owner indicating that they’re being asked to assume ownership of the file.
  1. The new owner accepts the ownership transfer request by creating or updating their file permission. The permission must include these settings: role=owner and transferOwnership=true. If the new owner is creating a new permission, an email notification is sent to the previous owner indicating that ownership has been transferred.

When this flow is reflected in the sample script, it becomes as follows.

Sample situation

It is considered a sample situation that the owner of a Google Spreadsheet of User “A” is transferred to User “B”.

Sample script

User “A” side

Before you use this script, please enable Drive API at Advanced Google services.

In order to prepare the owner transfer of the file, please run the following script by User “A”.

// This script is run by user "A".
// When this script is run, the user "B" is added as a writer for the file, and an email for authorization is sent.
// User "A" is the owner of a sample file.
// User "B" is the new owner.
function myFunction1() {
  const newOwnerEmail = "###@gmail.com"; // Email of user "B".
  const fileId = "###"; // The owner of the user of this file is user "A".

  Drive.Permissions.insert(
    { role: "writer", type: "user", value: newOwnerEmail, pendingOwner: true },
    fileId,
    { moveToNewOwnersRoot: true, supportsAllDrives: true }
  );
}

User “B” side

Before you use this script, please enable Drive API at Advanced Google services.

In order to prepare the owner transfer of the file, please run the following script by User “A”.

// This script is run by user "B".
// When this script is run, the owner of the file is transferred from user "A" to user "B".
// User "A" is the owner of a sample file.
// User "B" is the new owner.
function myFunction2() {
  const newOwnerEmail = "###@gmail.com"; // Email of user "B".
  const fileId = "###"; // The owner of the user of this file is user "A".

  Drive.Permissions.insert(
    { role: "owner", type: "user", value: newOwnerEmail },
    fileId,
    { moveToNewOwnersRoot: true, supportsAllDrives: true }
  );
}

Note

References

 Share!