Search code examples
google-apps-scriptgoogle-sheetsgoogle-apps-script-addon

could not open Documents in a Spreadsheet add-on. openByUrl( ) no permission


I have a speadsheet extension, which saves many docs metadata.

It uses an add-on menu to activate a merge files function, which uses DocumentApp.openBy..()

My question is a little like this.

I modified the manifest (appsscript.json) to have the following permissions:

It still does not work.

Here's my code.

makeMerge is triggered by an add-on menu button.

function onOpen(e) {
  var ui = SpreadsheetApp.getUi();
  ui.createAddonMenu().
    addItem("merge", 'uiTrigger').
    addToUi();
}


function uiTrigger() {
  makeMerge(SpreadsheetApp.getActiveSheet(), DriveApp.getRootFolder());
}


function makeMerge(sheet, folder) {
  if (folder === null || folder === undefined) {
     folder = DriveApp.getRootFolder();
  }

  var dataRows = sheet.getDataRange().getValues().length - 1;
  var names = sheet.getRange(2, 1, dataRows, 1).getValues();
  var docsRef = sheet.getRange(2, 8, dataRows, 1).getValues();
  var toDownload = sheet.getRange(2, 11, dataRows, 1).getValues();

  for (var i in toDownload) {
    var name = names[i][0];
    var docRef = docsRef[i][0];
    Logger.log(docRef);
    try {
      var doc = DocumentApp.openByUrl(docRef);
    } catch(error) {
      Logger.log(error);
    }
  }  
}  

I have no idea (I don't use spreadsheet custom function) why do I have the same issue? How do I give my script permission to open Documents?


Solution

  • DocumentApp.openByUrl() does not take a link from doc.getUrl() It seems not documented at offical website. Here's an example.

    // with a container-bound script, in this example
    function notWork() {
      var doc = DocumentApp.getActiveDocument();
      var docUrl = doc.getUrl();
      Logger.log(docUrl);  
      var newDoc = DocumentApp.openByUrl(docUrl);
    }
    

    Therefore, DocumentApp.openById() still works.

    function Worked() {
      var doc = DocumentApp.getActiveDocument();
      var docId = doc.getId();
      Logger.log(docId);  
      var newDoc = DocumentApp.openById(docId);
    }
    

    So, we can extract the id from the doc.getUrl(), which in the form of https://docs.google.com/open?id=YOUR_DOCUMENT_ID or https://docs.google.com/a/YOUR_DOMAIN/open?id=YOUR_DOCUMENT_ID

    function modifyFromNotwork(){
      var doc = DocumentApp.getActiveDocument();
      var docUrl = doc.getUrl();
      var docId = docUrl.slice(docUrl.indexOf("=")+1);
      Logger.log(docId);
      var newDoc = DocumentApp.openById(docId);
    }