我是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]
任何人都可以帮我解决这个问题吗?提前致谢! :)
答案 0 :(得分:1)
使用document.getActiveDocument()。该脚本必须是容器绑定的。 因此脚本必须与文档相关联。 您可以从文档的工具>脚本编辑器中打开它。
如果您只是创建一个新的脚本项目,它将找不到“活动文档”。
编辑: 即使脚本代码与Document关联,它也不适用于使用doGet的Web发布的应用程序。您必须首先使用诸如... openById('')
之类的方法获取文档