0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

OAuthスコープを../spreadsheets.currentonlyに設定したApps ScriptではSpreadsheetApp.getActiveRangeList()がエラーとなる

Posted at

Googleスプレッドシートで、選択したセル範囲の文字列(URL)をハイパーテキストに変換するためのGoogle Apps Script(GAS)を組んでいる時に出会った事象です。公式ドキュメントで書かれていることとは違う挙動を見つけたので、ご紹介します。

/* 
 * OAuth scopeを
 * https://www.googleapis.com/auth/spreadsheets.currentonly
 * に設定している場合
 */ 

// 選択されているセル範囲を取得する
const selectedRangeListNg = SpreadsheetApp.getActiveRangeList()
// 「Exception: その操作を実行する権限がありません。」

const selectedRangeListOk = SpreadsheetApp.getActiveSpreadsheet().getActiveRangeList()
// これなら普通に取得できる

Google Issue Trackerで類似事例へのコメントとして追記しておきましたが、そもそもその事例に対するIssue Tracker内の動きが1年半ほどないことから、しばらくは現状のままでしょう。

結論

スプレッドシートで選択中のセル範囲(複数可)を呼び出すためのメソッドSpreadsheetApp.getActiveRangeList()は、OAuthのスコープがhttps://www.googleapis.com/auth/spreadsheets(すべてスプレッドシートに対する閲覧・編集権限)でないと実行できません。

公式ドキュメントでは許容されていることになっているhttps://www.googleapis.com/auth/spreadsheets.currentonly(現在開いているスプレッドシートに対する閲覧・編集権限)ではException: その操作を実行する権限がありません。とエラーが返ってきます。

回避方法

そもそもマニフェストファイルappsscript.jsonでOAuthスコープを指定しないのであれば、この問題は発生しません。Apps Script側が自動的に../auth/spreadsheetsでユーザ承認を要求するためです。ベストプラクティスに従ってマニフェストファイルで必要最小限のOAuth権限だけを取得するようにしている優等生(笑)だけがこの問題にひっかかるわけです。

OAuth権限を変更せずに回避するならば、

SpreadsheetApp.getActiveRangeList()

SpreadsheetApp.getActiveSpreadsheet().getActiveRangeList()

と書き換えればいいです。いったんSpreadsheetオブジェクトとして現在開いているスプレッドシートを取得した上で、(SpreadsheetAppではなく)SpreadsheetのメソッドとしてgetActiveRangeListを呼び出せばいいということでしょう。

同様の制約があるメソッドが他にもありそう。getCurrentCell()など

Google Issue Trackerでも同様の報告はされており、SpreadsheetApp.getCurrentCell()も同様に公式ドキュメントで書かれているcurrentonlyスコープでは権限エラーを返されてしまうようです。

SpreadsheetApp.getCurrentCell not working with "currentonly" scope [170022856] - Visible to Public - Issue Tracker

検証していませんが、SpreadsheetAppから直接呼び出されるメソッドの一部に共通する事象かもしれません。ただ、上記Issueの報告日を見ると2020年10月で、2022年5月現在も担当がassignされていない... 今後も大きな動きはあまり期待できないでしょう。

参考資料

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?