"Cannot call DocumentApp.getUi() from this context" error
Asked Answered
I

4

9
function createAndSendDocument() {
// Create a new document with the title 'Hello World'
var ui = DocumentApp.getUi();
var response1 = ui.prompt('What should be Name of your Document', ui.ButtonSet.YES_NO);
var doc = DocumentApp.create(response1.getResponseText());

var response = ui.prompt('What should be content of your Document',  ui.ButtonSet.YES_NO);
// Add a paragraph to the document
var paragraph  = prompt("What should be content of your Document")
doc.appendParagraph(response.getResponseText());

// Save and close the document
doc.saveAndClose();

// Get the URL of the document
var url = doc.getUrl();

// Get the email address of the user
var response2 = ui.prompt('What should be content of your Document', ui.ButtonSet.YES_NO)
var emailAddress = response2.getResponseText();

// Send the user an email with a link to the document
GmailApp.sendEmail(emailAddress,
                 'Hello from my first Google Apps Script!',
                 'Here is a link to a document created by my ' +
                 'first Google Apps Script: ' + url);
}

This the code I entered, and it resulted in an Error:

"Cannot call DocumentApp.getUi() from this context. (line 3, file "Code")"

What is the problem in the code?

Intramuscular answered 17/9, 2013 at 3:32 Comment(0)
E
11

If it is in a spreadsheet, not a document, it will give this error.

Therfore you have to use the spreadsheet alternative

function onOpen() {
   var ss = SpreadsheetApp.getActive();
   var items = [
      {name: 'First item', functionName: 'menuItem1'},
      null, // Results in a line separator.
      {name: 'Second item', functionName: 'menuItem2'}
   ];
   ss.addMenu('Custom Menu', items);
}

https://developers.google.com/apps-script/guides/menus

Educatee answered 8/11, 2013 at 7:44 Comment(0)
M
2

That method can only be invoked from a Document-contained script. A script that is contained in a spreadsheet or form, or one that is stand-alone, does not have access to a Document User Interface instance.

Materiality answered 17/9, 2013 at 4:13 Comment(0)
C
0

Although it's been a long time, I had this problem and decided to share the solution that solved it for me.

In my case, this error was appearing and what I did was close my script editor, open the document I was working on and access the script editor through the file menu. With this, the script becomes associated with the file.

Probably what could be happening is that the script being written is not associated with the file or document. And performing these steps can solve it.

Always run the script editor from the file menu.

Chicalote answered 27/4, 2023 at 13:35 Comment(0)
D
0

Your code is fine, you just need to run it a certain way.

Simply create a test deployment for the current document and it should run when you reload the document.

Durward answered 25/5, 2023 at 18:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.