为什么 .getUrl 不能在此代码中工作?

Why can't .getUrl work in this code?

我是 Google Script 的新手,决定试用位于底部的文档代码。代码位于下方:

function createAndSendDocument() {
   // Create a new Google Doc named 'Hello, world!'
   var doc = DocumentApp.create('Hello, world!');

   // Access the body of the document, then add a paragraph.
   doc.getBody().appendParagraph('This document was created by Google Apps Script.');

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

   // Get the email address of the active user - that's you.
   var email = Session.getActiveUser().getEmail();

   // Get the name of the document to use as an email subject line.
   var subject = doc.getName();

   // Append a new string to the "url" variable to use as an email body.
   var body = 'Link to your doc: ' + url;

   // Send yourself an email with a link to the document.
   GmailApp.sendEmail(email, subject, body);
}

代码工作得很好,但由于我不希望每次 运行 都创建一个新文档,所以我将代码编辑为:

function sendDocument() {
   // Get the name of the document to use as an email subject line.
   var doc = DocumentApp.getActiveDocument();

   // Get the email address of the active user - that's you.
   var email = Session.getActiveUser().getEmail();

   // Append a new string to use as an email body.
   var body = 'Link to your doc: ' + doc.getUrl() + '. Happy editing! :D';

   // Send yourself an email with a link to the document.
   GmailApp.sendEmail(email, doc, body);
}

但是,我无法 运行 上述代码,并弹出一条错误消息:

TypeError: Cannot call method "getUrl" of null. (line 9, file "")

这是我的执行记录:

[15-10-03 10:13:26:875 PDT] Starting execution
[15-10-03 10:13:26:881 PDT] DocumentApp.getActiveDocument() [0 seconds]
[15-10-03 10:13:26:883 PDT] Session.getActiveUser() [0 seconds]
[15-10-03 10:13:26:883 PDT] User.getEmail() [0 seconds]
[15-10-03 10:13:26:886 PDT] Execution failed: TypeError: Cannot call method "getUrl" of null. (line 9, file "Code") [0.003 seconds total runtime]

谁能帮我解决这个问题?提前致谢! :)

要使用document.getActiveDocument()。该脚本必须是容器绑定的。 所以脚本必须与文档相关联。 您可以从文档的工具 > 脚本编辑器中打开它。

如果你只是在其中新建一个脚本项目,它会找不到"Active document"。

编辑: 即使脚本代码与文档相关联,它也不适用于使用 doGet 的网络发布的应用程序。您必须首先使用 ...openById('')

等方法获取文档