Home > Enterprise >  How do I grab URL in Apps Script (.gs) and hand it to a .html script?
How do I grab URL in Apps Script (.gs) and hand it to a .html script?

Time:04-22

This is my first question here and I am pretty new to js and html so please excuse if I'm missing something obvious.

Goal: I want to create a script, that creates a Folder in your Google Drive but only if it's not already existing. In that folder it should create a .txt that contains certain information. After that, I want a new Tab to automatically open the URL of the newly created txt-file.

If I insert a normal URL in my .html (like "https://www.google.com") it all works perfectly fine. However I'm stuck at the part where the Apps Script hands over the grabbed Url of the newly created file to my html.

Any help is appreciated!

Google Apps Script Code (Code.gs):

function myFunction() {

  var FData = "Very important Data"       
  
  var destFolder = DriveApp.getFoldersByName("Folder");     //create Drive folder if not already created
  var destFolder = destFolder.hasNext() ? 
    destFolder.next() : DriveApp.createFolder("Folder");

  var fileName = "Status.txt";                              //create txt file in that folder and add data to it
  var newFile = destFolder.createFile(fileName,FData);
  var url = newFile.getUrl();                               //?GIVE THIS URL TO openUrl.html?

  var htmlOutput = HtmlService.createHtmlOutputFromFile('openUrl').setHeight(100);
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Opening...');
}

HTML (openUrl.html):

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
     var urlToOpen = url;                     //insert grabbed Url here
     var winRef = window.open(urlToOpen);
     google.script.host.close();
    </script>
  </head>
  <body>
    
  </body>
</html>

CodePudding user response:

In your script, how about the following modification?

Google Apps Script side:

function myFunction() {
  var FData = "Very important Data"
  var destFolder = DriveApp.getFoldersByName("Folder");
  var destFolder = destFolder.hasNext() ? destFolder.next() : DriveApp.createFolder("Folder");
  var fileName = "Status.txt";
  var newFile = destFolder.createFile(fileName, FData);
  var htmlOutput = HtmlService.createTemplateFromFile('openUrl');
  htmlOutput.url = newFile.getUrl();
  SpreadsheetApp.getUi().showModalDialog(htmlOutput.evaluate().setHeight(100), 'Opening...');
}

HTML & Javascript side:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
     var urlToOpen = "<?!= url ?>";
     var winRef = window.open(urlToOpen);
     google.script.host.close();
    </script>
  </head>
  <body>
  </body>
</html>
  • When myFunction() is run, a dialog is opened by HTML including url using HTML template.

Reference:

  • Related