Search code examples
google-apps-scriptgoogle-docs

How to generate a Google Docs with an embedded AppScript, using Apps Script?


I'm interested in generating a Google Document with a particular Apps Script from my library. The way I have been creating the Documents has been through basically, Jeff Everhart's code as seen here.

Is it possible that the code be changed as to have the new Google Docs have an embedded Apps Script right from the get go?

My reduced code:

  function createNewGoogleDocs() {
      const googleDocTemplate = DriveApp.getFileById('The template ID goes here');
      const destinationFolder = DriveApp.getFolderById('The destination folder ID goes here');

      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
      const rows = sheet.getDataRange().getValues();
  
  
    rows.forEach(function(row, index) {
      if (index === 0 ) return;
      if(row[rows[0].length - 1]) return;


      const copy = googleDocTemplate.makeCopy(`First Column Name (${row[0]})`, destinationFolder);
      const doc = DocumentApp.openById(copy.getId());
    
      // Hopefully here we can have the addition of the the Apps Script on the new Docs

      doc.saveAndClose();
      const url = doc.getUrl();
      sheet.getRange(index+1, rows[0].length).setValue(url);


    })

  }

Solution

  • If your goal is to create an Apps Script project bound to a Doc, you have to create it from that particular document. As it is said on the docs:

    A script is bound to a Google Sheets, Docs, Slides, or Forms file if it was created from that document rather than as a standalone script. The file that a bound script is attached to is called a "container." Bound scripts generally behave like standalone scripts except that they do not appear in Google Drive, they cannot be detached from the file they are bound to, and they gain a few special privileges over the parent file.

    If your end goal is to create a Doc with an embedded Apps Script from a different Apps Script project, you would have to first create that Doc/script as a template and then use makeCopy to create a copy of the Doc/script.

    I am documenting this answer to help other people on this community, please feel free to leave a comment in your need further assistance.