Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google apps script 从Google站点运行Webapp中发布的函数_Google Apps Script_Google Sheets_Cors_Google Sites - Fatal编程技术网

Google apps script 从Google站点运行Webapp中发布的函数

Google apps script 从Google站点运行Webapp中发布的函数,google-apps-script,google-sheets,cors,google-sites,Google Apps Script,Google Sheets,Cors,Google Sites,我想在谷歌网站的webapp中运行一个函数作为onloadfunction code.gs function doGet(e){ return HtmlService.createHtmlOutputFromFile("page"); } function myfunc(datavalues) { var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEET-ID-IS-HERE'; /

我想在谷歌网站的webapp中运行一个函数作为
onload
function

code.gs

function doGet(e){
  return HtmlService.createHtmlOutputFromFile("page"); 
}

function myfunc(datavalues) {
      var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEET-ID-IS-HERE';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
      activeSheet.getRange(1,1).setValue(datavalues[0]);
      activeSheet.getRange(1,2).setValue(datavalues[1]);
     // ---------------------------------------------------- //
}
    function doGet(e){
     console.log("get request");
      return HtmlService.createHtmlOutputFromFile("page"); 
    }
    
    function myfunc(datavalues) {
          var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEET-ID-IS-HERE';
         // Current Active Sheet
         var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
         var activeSheet = activeGoogleSheet.getActiveSheet();
          activeSheet.getRange(1,1).setValue(datavalues[0]);
          activeSheet.getRange(1,2).setValue(datavalues[1]);
         // ---------------------------------------------------- //
    }
// Post method
function doPost(datavalues){
  console.log("post Request");
// check the parameters


 if(typeof e !== 'undefined')
  var datavalues =  JSON.stringify(JSON.parse(e.parameter)); 
  console.log(datavalues);
  var sheetURL = 'https://docs.google.com/spreadsheets/d/URL/';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
     // first empty row
     var dataRow = activeSheet.getDataRange().getLastRow()+1;
     // ---------------------------------------------------- //
     // writing data to the sheet
     // ---------------------------------------------------- //
          activeSheet.getRange(dataRow,1).setValue(datavalues['a']);
         activeSheet.getRange(dataRow,2).setValue(datavalues['b']);
     // ---------------------------------------------------- // 
   return ContentService.createTextOutput(JSON.stringify(e));
    }
// Post method
function doPost(e){
  //console.log(JSON.stringify(e,null, 2));
  // check the parameters
  if(typeof e !== 'undefined')
  console.log(e);
  var datavalues = e.parameter; 
  var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEETURL/';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
     // first empty row
     var dataRow = activeSheet.getDataRange().getLastRow()+1;
     // ---------------------------------------------------- //
     // writing data to the sheet
     // ---------------------------------------------------- //

          activeSheet.getRange(dataRow,1).setValue(datavalues.a);
     
         activeSheet.getRange(dataRow,2).setValue(datavalues.b);
     // ---------------------------------------------------- // 
   return ContentService.createTextOutput(JSON.stringify(e));
}
page.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  
    <body>
  </body>
  
  
  <script>
       // function run from code.gs
       function runfunc(values){
                 google.script.run.myfunc(values);
       }
       
  </script>
</html>
嵌入谷歌网站的代码:

<!DOCTYPE html>
<html>
<script src="https://script.google.com/a/macros/s/WEBAPPURL/exec"></script>
<script>
    function loadFunc(){
         var values = ['aaaa',123];
         runfunc(values);       
 }
</script>


<body onload='loadFunc()'>

<body/>
</html>
<!DOCTYPE html>
<html>
<script>
function postRequest(url, data) {
  return fetch(url, {
    method: 'POST', 
    credentials: 'omit';
    headers: {'Accept': 'application/json',
    'Content-Type': 'application/json'
    }
    body:  JSON.stringify(data);
 });
}

function onloadfunc(){
console.log('loadding');
var data = {'a':'xxx','b':'ppp'};
postRequest('https://script.google.com/a/macros/s/WEBAPP/exec', data).then(function(response) {
    console.log("ok");
}).catch(function(error) {
    console.log(error);
}
</script>


<body onload="onloadfunc()">
<body/>


</html>
code.gs

function doGet(e){
  return HtmlService.createHtmlOutputFromFile("page"); 
}

function myfunc(datavalues) {
      var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEET-ID-IS-HERE';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
      activeSheet.getRange(1,1).setValue(datavalues[0]);
      activeSheet.getRange(1,2).setValue(datavalues[1]);
     // ---------------------------------------------------- //
}
    function doGet(e){
     console.log("get request");
      return HtmlService.createHtmlOutputFromFile("page"); 
    }
    
    function myfunc(datavalues) {
          var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEET-ID-IS-HERE';
         // Current Active Sheet
         var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
         var activeSheet = activeGoogleSheet.getActiveSheet();
          activeSheet.getRange(1,1).setValue(datavalues[0]);
          activeSheet.getRange(1,2).setValue(datavalues[1]);
         // ---------------------------------------------------- //
    }
// Post method
function doPost(datavalues){
  console.log("post Request");
// check the parameters


 if(typeof e !== 'undefined')
  var datavalues =  JSON.stringify(JSON.parse(e.parameter)); 
  console.log(datavalues);
  var sheetURL = 'https://docs.google.com/spreadsheets/d/URL/';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
     // first empty row
     var dataRow = activeSheet.getDataRange().getLastRow()+1;
     // ---------------------------------------------------- //
     // writing data to the sheet
     // ---------------------------------------------------- //
          activeSheet.getRange(dataRow,1).setValue(datavalues['a']);
         activeSheet.getRange(dataRow,2).setValue(datavalues['b']);
     // ---------------------------------------------------- // 
   return ContentService.createTextOutput(JSON.stringify(e));
    }
// Post method
function doPost(e){
  //console.log(JSON.stringify(e,null, 2));
  // check the parameters
  if(typeof e !== 'undefined')
  console.log(e);
  var datavalues = e.parameter; 
  var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEETURL/';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
     // first empty row
     var dataRow = activeSheet.getDataRange().getLastRow()+1;
     // ---------------------------------------------------- //
     // writing data to the sheet
     // ---------------------------------------------------- //

          activeSheet.getRange(dataRow,1).setValue(datavalues.a);
     
         activeSheet.getRange(dataRow,2).setValue(datavalues.b);
     // ---------------------------------------------------- // 
   return ContentService.createTextOutput(JSON.stringify(e));
}
这样,就调用了
doPost
,并且它可以工作!!! 现在我唯一的问题是我的字典传错了。 在站点中,它是
{'a':'xxx','b':'ppp'}
,但传递的总参数如下所示(console.log(e)的结果):


以某种方式添加了额外的
=
,然后字典按原样传递。

您可以在启动时使用jQuery加载函数。如下所示,在html文件中添加以下代码:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
    loadFunc();
  });

function loadFunc(){
var values = ['aaaa',123];
  google.script.run
        .withSuccessHandler(function(data) {
            console.log('Success')
          })
        .withFailureHandler(function(msg) {
            console.log('Error : '+msg);
          })
        .myfunc(values);
}
</script>

$(函数(){
loadFunc();
});
函数loadFunc(){
var值=['aaaa',123];
google.script.run
.withSuccessHandler(函数(数据){
console.log('Success')
})
.withFailureHandler(函数(msg){
console.log('错误:'+msg);
})
.myfunc(值);
}

然后在站点上嵌入带有IFRAME的页面,它将加载空白页并执行该函数。 您可以指定较小的iframe大小,以便iframe只使用较小的空间

斯泰芬尼

目标:
  • 在域中发布的WebApp中运行特定函数,使用Google apps脚本和
    • 访问:来自域的任何人
    • 在同一域中发布的新Google站点
问题:
  • CORS:谷歌应用脚本web应用(以下简称Gas-webapp)和谷歌网站中的用户代码(以下简称Gs-webapp)都运行在不同来源的iFrame中-
    https://[different\u URL].googleusercontent.com
    沙盒中
脚本流:
  • 使用
    Fetch
    api将
    POST
    数据从谷歌网站发布到web应用程序
  • 接收来自谷歌网站的
    POST
    请求并执行该功能
要求阅读:
笔记:
  • Gas web app默认情况下为任何经过身份验证的CORS请求提供以下CORS响应标头:

    • 访问控制允许原点:
  • 但是,如果请求的内容未经验证,或者脚本出错,您将被重定向到Google的登录页面/错误页面;两个网页都没有设置
    访问控制允许源站
    ,所有网页的访问都将被阻止

  • 上述未经验证的请求的唯一例外是发布Gas web应用程序,其访问权限为:
    任何人,
    甚至匿名

  • Gas web应用程序不允许
    选项
    方法。因此,所有请求都将失败

  • 与gas web app兼容的唯一剩余CORS选项是,浏览器未预引导的

  • 但是,简单的
    POST
    请求基本上是未经验证的。在这个脚本中,我们在请求中使用包含第三方凭据的。这里,我们关注的是用户帐户的谷歌凭证。通过使用此选项,我们实际上是在使用用户帐户的Google凭据进行身份验证。使用此选项必须满足以下条件:

    • 用户必须登录到Google,以便在post请求中发送登录cookie
    • 必须在浏览器中启用第三方cookie,因为iframe的来源不同
  • 可以将设置为
    cors
    no cors

  • 但是,如果设置了
    cors
    ,则根据,gas web应用程序必须提供以下响应标题,以使用凭据发布请求:

    访问控制允许凭据

gas webapp未提供此功能。虽然请求将被发送(因为它不是预引导的),但响应无法接收(不是共享的),即,
doPost
仍将运行,但gs webapp无法接收响应

  • 如果未设置cors,fetch将返回一个(空响应)

    不透明过滤响应是一种过滤响应,其类型为“不透明”,URL列表为空列表,状态为0,状态消息为空字节序列,标题列表为空,正文为空,尾部为空

  • 本质上,当访问设置为
    any
    (非匿名)时,您可以从gs web app到gas web app进行单向通信

  • POST
    使用
    应用程序/x-www-form-urlencoded
    发出的请求必须是格式字符串:
    input1=1&input2=4
    。可以用来从对象中制作这样的字符串

片段:

函数postRequest(url、数据){
返回获取(url{
方法:“POST”,
模式:'无cors'、//或'cors':尽管请求失败,doPost仍将执行
标题:{
“接受”:“*/*”,//**已修改**
“内容类型”:“应用程序/x-www-form-urlencoded”
},
凭据:'include',//访问浏览器cookie中的凭据
正文:数据
});
}
函数onloadfunc(){
console.log(“加载”);
var data=(新的URLSearchParams({'a':'xxx','b':'ppp'})).toString();//**已修改**
postRequest('https://script.google.com/a/WEBAPP/exec,然后(函数(响应){
//************不透明响应:不会收到任何信息************
var div=document.getElementById('errorOutput');
response.text(res=>
div.innerHTML=“响应”+res)
控制台日志(“ok”);
}).catch(函数(错误){
var div=document.getElementById('errorOutput');
div.innerHTML=“error”+错误;
console.log(错误);});
}
code.gs

function doGet(e){
  return HtmlService.createHtmlOutputFromFile("page"); 
}

function myfunc(datavalues) {
      var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEET-ID-IS-HERE';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
      activeSheet.getRange(1,1).setValue(datavalues[0]);
      activeSheet.getRange(1,2).setValue(datavalues[1]);
     // ---------------------------------------------------- //
}
    function doGet(e){
     console.log("get request");
      return HtmlService.createHtmlOutputFromFile("page"); 
    }
    
    function myfunc(datavalues) {
          var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEET-ID-IS-HERE';
         // Current Active Sheet
         var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
         var activeSheet = activeGoogleSheet.getActiveSheet();
          activeSheet.getRange(1,1).setValue(datavalues[0]);
          activeSheet.getRange(1,2).setValue(datavalues[1]);
         // ---------------------------------------------------- //
    }
// Post method
function doPost(datavalues){
  console.log("post Request");
// check the parameters


 if(typeof e !== 'undefined')
  var datavalues =  JSON.stringify(JSON.parse(e.parameter)); 
  console.log(datavalues);
  var sheetURL = 'https://docs.google.com/spreadsheets/d/URL/';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
     // first empty row
     var dataRow = activeSheet.getDataRange().getLastRow()+1;
     // ---------------------------------------------------- //
     // writing data to the sheet
     // ---------------------------------------------------- //
          activeSheet.getRange(dataRow,1).setValue(datavalues['a']);
         activeSheet.getRange(dataRow,2).setValue(datavalues['b']);
     // ---------------------------------------------------- // 
   return ContentService.createTextOutput(JSON.stringify(e));
    }
// Post method
function doPost(e){
  //console.log(JSON.stringify(e,null, 2));
  // check the parameters
  if(typeof e !== 'undefined')
  console.log(e);
  var datavalues = e.parameter; 
  var sheetURL = 'https://docs.google.com/spreadsheets/d/SHEETURL/';
     // Current Active Sheet
     var activeGoogleSheet = SpreadsheetApp.openByUrl(sheetURL);
     var activeSheet = activeGoogleSheet.getActiveSheet();
     // first empty row
     var dataRow = activeSheet.getDataRange().getLastRow()+1;
     // ---------------------------------------------------- //
     // writing data to the sheet
     // ---------------------------------------------------- //

          activeSheet.getRange(dataRow,1).setValue(datavalues.a);
     
         activeSheet.getRange(dataRow,2).setValue(datavalues.b);
     // ---------------------------------------------------- // 
   return ContentService.createTextOutput(JSON.stringify(e));
}
//Post方法
函数doPost(e){
log(JSON.stringif