Max
Max

Reputation: 186

Can I use DocumentApp.openById() with read only permission?

I am creating a Google Apps Script add-on that is for a Google Spreadsheet, but it needs to be able to access the content of a separate Google Doc, which I am doing using DocumentApp.openById(). I have given the script these scopes:

"oauthScopes": [
    "https://www.googleapis.com/auth/documents.readonly",
    "https://www.googleapis.com/auth/script.container.ui",
    "https://www.googleapis.com/auth/spreadsheets.currentonly"
  ]

But apparently, that's not enough. The script is telling me it needs the https://www.googleapis.com/auth/documents permission to work properly. However, it seems excessive to give the add-on permission to edit ALL Google Docs files when it just needs to be able to view the content of one. Am I missing something? Is there a way to give it read-only access to a separate Google Docs file?

Here is the function I am using for testing, with most of the document ID censored out:

function getDoc() {
  var id = '1NLH----------------------------------------'
  var templateFile = DocumentApp.openById(id)
  var templateText = templateFile.getBody().getText()
  Logger.log(templateText)
}

Thanks!

Upvotes: 2

Views: 1878

Answers (1)

Tanaike
Tanaike

Reputation: 201643

I believe your goal as follows.

  • You want to retrieve the text data from Google Document using the following script.

      function getDoc() {
        var id = '1NLH----------------------------------------'
        var templateFile = DocumentApp.openById(id)
        var templateText = templateFile.getBody().getText()
        Logger.log(templateText)
      }
    
  • You want to achieve this using the scope of https://www.googleapis.com/auth/documents.readonly and Google Apps Script.

Issue and workaround:

In the current stage, DocumentApp.openById of Document service is used, it is required to use the scope of https://www.googleapis.com/auth/documents. It seems that this is the current specification. So, in this answer, as a workaround, I would like to propose to use Google Docs API instead of Document service. When Google Docs API is used, your script can be achieved using the scope of https://www.googleapis.com/auth/documents.readonly.

When your above script is modified using Google Docs API, it becomes as follows.

Sample script:

Before you use this script, please enable Google Docs API at Advanced Google services. This script can work with only the scope of https://www.googleapis.com/auth/documents.readonly.

function myFunction() {
  const documentId = "###"; // Please set the Document ID.

  const obj = Docs.Documents.get(documentId);
  const text = obj.body.content.reduce((s, c) => {
    if (c.paragraph && c.paragraph.elements) {
      s += c.paragraph.elements.map(e => e.textRun.content).join("");
    }
    return s;
  }, "");
  console.log(text)
}

Reference:

Upvotes: 6

Related Questions