javascript可以读取从app脚本函数返回的字符串吗?

时间:2016-08-15 22:37:34

标签: javascript string google-apps-script return

在Google-Apps-Script中我创建了一个函数,该函数返回一个包含电子表格文件ID的字符串(此ID因用户而异,因为它是从模板复制的新文件)。

function findSheet(){ 
//Opens User's Google Drive and searches files for a spreadsheet called "blahblah" and returns the active spreadsheet
var files = DriveApp.getFilesByName("blahblah");
var file = files.next();
var newID = file.getId();
Logger.log(newID);
return newID;
}

Logger.log(newID)显示测试中文件的ID名称。但是,当我尝试向返回的id字符串发起一个javascript变量时,它变为未定义。

<script>
var idname;
idname = google.script.run.findSheet();
alert(idname);

我有另一个谷歌脚本应用程序功能(从javascript调用),它使用该id字符串变量作为参数,以便将用户输入从我的html页面写入他们的谷歌电子表格作为网络应用程序的一部分,但id来自javascript的名称作为undefined进入,并且该函数不起作用。

有什么我不知道为什么在javascript调用时应用程序脚本字符串是未定义的?

我尝试使用idname.toString()进行修复但是当我使用alert(idname)或document.write(idname)或重写段落时它仍显示为undefined

<p idname="showmeID"></p>
<script>
document.showmeID.innerHTML.idname

1 个答案:

答案 0 :(得分:2)

  

google.script.run是HTML服务页面中可用的异步客户端JavaScript API,可以调用服务器端的Apps脚本功能。

根据documentation,此API是异步的,不会直接返回值。相反,它会在回调函数中返回值。

google.script.run
    .withFailureHandler(function(err){
        // callback function that will be executed when some error will occur.
        // Error object is passed as the first argument.
        console.log("failure handler", err)
    })
    .withSuccessHandler(function(res){
        // here withSuccessHandler runs when your findSheet function runs successfully.
        // value returned from google app script will be passed as the first argument of this callback function.
        // So you will receive the value returned from GAS in variable `res`.
        console.log("response from findSheet function", res)
    })
    .findSheet();