Home > Back-end >  Can't download files from Google Drive using GAS
Can't download files from Google Drive using GAS

Time:12-08

I have been using a simple Google Apps Script code to download a file from my Google Drive to my local computer.

var dlUrl = "https://drive.google.com/uc?export=download&id="   file.getId();

  // Open a dialog and run Javascript for downloading the file.
  var str = '<script>window.location.href="'   dlUrl   '"</script>';
  var html = HtmlService.createHtmlOutput(str);
  SpreadsheetApp.getUi().showModalDialog(html, "Downloading invoice ... please wait");

  // This is used for closing the dialog.
  Utilities.sleep(3000);
  file.setTrashed(true);
  var closeHtml = HtmlService.createHtmlOutput("<script>google.script.host.close()</script>");
  SpreadsheetApp.getUi().showModalDialog(closeHtml, "Downloading invoice ... please wait");

This code has been working for over a year and then suddenly stopped working a few days ago with no changes to the code. When I run it, I now get the message: "403. That's an error. We're sorry, but you do not have access to this page. That's all we know."

I know the file exists and can be accessed because if I take the string in dlUrl and put it in the address bar of my browser, the file downloads without trouble.

I have also:

  • Signed out of all other Google accounts, and have signed in only to the account that owns the file.
  • Removed all saved passwords to the account
  • Attempted to change the file permissions to universal EDIT permissions

While I do tinker with Google Apps Script, I consider myself a beginner still and would appreciate any suggestions on what I should try. Thank you very much for your help.

CodePudding user response:

In this case, please modify as follows.

From:

var str = '<script>window.location.href="'   dlUrl   '"</script>';

To:

var str = '<script>window.open("'   dlUrl  '", "_blank")</script>';
  • window.location.href is the property of window. Ref window.open is a method of window. Ref window.open can use _blank while window.location.href cannot use it. Namely, window.open can open the URL as a new window. I thought that this might be the reason for this situation.
  • And, when _self is used as the target of window.open, the same error with you like 403. That’s an error. We're sorry, but you do not have access to this page. That’s all we know. occurs. And, when _top and _parent are used, no download occurs. So I proposed to use _blank.

References:

  • Related