我正在开发一个更大的项目,其中一部分是设计自定义公式,从ScanPower.com通过Google Apps脚本中的UrlFetchApp的urlFetch方法获取与ASIN(亚马逊上下文)相关的信息。
问题是,当我在电子表格中使用这些自定义公式作为普通的电子表格函数时,它可以正常工作并获取数据。如果我通过菜单项调用它,它仍然可以。
现在,使用带有按钮的侧边栏html来调用相同的函数,函数内部使用的urlFetch会产生500错误。这个函数是通过google.script.run调用的。当我尝试在脚本编辑器中以调试模式运行它时会发生同样的错误。
任何人都可以帮忙解决这个问题,或者我在这里做些蠢事。
function onOpen(e) {
//menu creation
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Formulas')
.addItem('Get Data Example', 'showExample')
.addItem('Get Fresh Data', 'queryNetPayout')
.addToUi();
};
function showExample() {
var html = HtmlService.createHtmlOutputFromFile('example')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Formulas Configuration')
.setWidth(300);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showSidebar(html);
};
//this is example.html used in sidebar
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
///////////////////////////////////////////////////////////////////////
function getFreshDataJS()
{
alert("data call rcvd");
google.script.run.queryNetPayout();
};
/////////////////////////////////////////////////////////////////////////
//SCRIPT ends here
</script>
</head>
<body>
<h3>Formula</h3>
<hr />
<form id = "configFormID" name="configForm" role="form">
<input name="getDataButton" type="button"
value="Get Data" id="getDataBtnID" onclick="getFreshDataJS()" />
</form>
</body>
</html>
//short version of function requiring urlfetch
///////////////////////////////////////////////////////////////////
function queryNetPayout(query, priceValue)
{
//for the time being, fixing the input values
query = "B00KSCABDG";
priceValue = "";
var fullData = {
output: { },
error: null,
type: "fresh query"
};
var headers = {
"Authorization" : "Basic " + scanpKey,//key credentials cannot be shared
"X-Requested-With" : "XMLHttpRequest"
};
var params = {
"method":"GET",
"headers": headers
//"muteHttpExceptions" : true
};
//this urlfetch stucks when called through google.script.run
//Or called through debug mode from script project
//works fine if called through custom formula from spreadsheet
//or called through menu item from custom menu
var res = UrlFetchApp.fetch("https://unity.scanpower.com/net-payout?upc=" + query + "&price=" + priceValue + "&marketplace=US&detail=", params);
var status = res.getResponseCode();
if(status != 200)
{
fullData.error = "Response Code: " + status;
return fullData;
}
var body = res.getContentText();
fullData.output = JSON.parse(body);
return fullData;//error = null => successful
};