Use Google Web App URL Parameter As Part Of Function - google-apps-script

I'm trying to use a parameter in a Google web app url to select which tab of a Google Sheet I want to extract data from. The request for data is made via a Chatfuel JSON GET request, which pulls data from the spreadsheet tab and returns it as formatted json code into the chatbot.
When I run the request without passing a parameter and manually enter the sheet tab name into the doGet function of the Google Sheet script as below it works fine.
URL - https://script.google.com/macros/s/xxx-xxx-xxx/exec
function doGet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Retail");
var data = sheet.getDataRange().getValues();
elements = create_elements(data)
if (elements.length != 0) {
return buildImageGallery(elements);
} else {
return notFound()
}
}
I just can't quite figure out how to take a parameter from a url (e.g "type"), and then use that as part of the doGet function - this is what I'm roughly trying to do...
URL - https://script.google.com/macros/s/xxx-xxx-xxx/exec?type=Retail
function doGet() {
var type = e.parameter.type;
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(type);
var data = sheet.getDataRange().getValues();
elements = create_elements(data)
if (elements.length != 0) {
return buildImageGallery(elements);
} else {
return notFound()
}
}
I'm sure it's soemthing simple, but I'm just getting started with this coding stuff so I'm not sure what I need to change. Thanks in advance for your help.

Does function doGet(e) work?
Is it a typo or you missed it? The e parameter inside the function.

Related

Google sheets custom function data disappears when viewing site as html after 20 minutes

I am trying to understand why a custom google sheet script can initially pull in JSON data when I have the sheet open, as defined in cell(A1).
20 minutes after closing the google sheet in the browser, I access the published html page of that sheet and the data is not displayed.
I wanted to see a proof of concept for a google-apps-script function that is run within google sheets and fetches a JSON page and displays the data as a google sheets table in html.
I went through this tutorial which gives an example function https://www.youtube.com/watch?v=EXKhVQU37WM&t=2s
* Imports JSON data to your spreadsheet Ex: IMPORTJSON("http://myapisite.com","city/population")
* #param url URL of your JSON data as string
* #param xpath simplified xpath as string
* #customfunction
*/
function IMPORTJSON(url,xpath){
try{
// /rates/EUR
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var json = JSON.parse(content);
var patharray = xpath.split("/");
//Logger.log(patharray);
for(var i=0;i<patharray.length;i++){
json = json[patharray[i]];
}
//Logger.log(typeof(json));
if(typeof(json) === "undefined"){
return "Node Not Available";
} else if(typeof(json) === "object"){
var tempArr = [];
for(var obj in json){
tempArr.push([obj,json[obj]]);
}
return tempArr;
} else if(typeof(json) !== "object") {
return json;
}
}
catch(err){
return "Error getting data";
}
}
When I open the sheet in cell A1 the function IMPORTJSON is called. I get an error for around 5 seconds("error, unknown function") and then the data is fetched and correctly displayed.
When I go to the link of the published sheet page as html (file -> share -> publish to web) 20 minutes after closing the sheet, I get a #NAME? error in the cell with the function.
What the error looks like in chrome.
google doc: https://docs.google.com/spreadsheets/d/1iDuaKn5S6jnRJmGW6iENvQ6-cE5BK-R-ZEnIVBPJc5w/edit?usp=sharing
html published page
https://docs.google.com/spreadsheets/d/e/2PACX-1vRllWzf7g-lARy_PgRUNHc0Jz1AB9W8nN0tmfvLQzE4rpwq3j3C7DwiD154K6_UeilDUpkLSGO8UIJT/pubhtml?gid=0&single=true
Here is the function as defined in the Apps Script for the sheet
https://www.chicagocomputerclasses.com/google-sheets-import-json-importjson-function/
Function call(cellA1) (XXX is API key):
=IMPORTJSON("http://data.fixer.io/api/latest?access_key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&symbols=USD,AUD,CAD,PLN,MXN&format=1","rates")
Why can't the data pulled by the function(when the sheet is open in the browser) be static on the sheet when the google sheet is closed, and the html version of the sheet is accessed?
I haven't called the function in the meantime by accessing the google sheet.
Unfortunately, this is a bug in the google sheet framework. Loading the html version of a sheet does not allow the sheet to call custom functions.
https://issuetracker.google.com/issues/218993622

Trying to pull the Redirect URL from a given URL in Google Sheets, with only the Redirect URL printed

So I have a list of URLs in Google Sheets which all redirect when clicked on. I had been manually going through and clicking the URLs, copying the Redirect URL, and then pasting it into a new column of the spreadsheet. Problem is there thousands, and I want to be more efficient. Currently I have this code:
function getRedirects(url) {
var params = {
'followRedirects': false,
'muteHttpExceptions': true
};
var followedUrls = [url];
while (true) {
var res = UrlFetchApp.fetch(url, params);
if (res.getResponseCode() < 300 || res.getResponseCode() > 399) {
return followedUrls;
}
var url = res.getHeaders()['Location'];
followedUrls.push(url);
}
}
The problem is, this code prints both the original URL as well as the Redirect URL. Is there any way to have it print ONLY the Redirect URL? I am hoping to print only the Redirect URL so that I can drag the function =getRedirects(url) down the column on the spreadsheet.
Any help is greatly appreciated!
The line var followedUrls = [url]; will add the original URL as the first array value of followedUrls because of the url parameter was added on its creation. Thus, when you run your custom function, for example getRedirects(A1), the followedUrls array will return the original URL and then the redirected URL on your sheet.
Additional recommendation:
Instead using the reverse shift() method, you can also just remove url parameter on your declaration of the var followedUrls = [];
Your custom function will return an array of URLs that let you see the full redirect flow, which may contain multiple redirects. That is useful functionality, so you may want to keep your current getRedirects() function as is, and create another function that returns just the final redirect destination. Try this:
function getFinalRedirect(url) {
return getRedirects(url).pop();
}
Then, in your spreadsheet formulas, use =getFinalRedirect(A2) instead of =getRedirects(A2).

Triggering GAS function via URL

Very new to this, but giving it a shot. I am trying to set up an Arduino motion sensor to trigger a script. At this point, my goal is to trigger a script via URL. I found this code below that I am working through, but I continue to get this error when running/debugging.
TypeError: Cannot read property "parameter" from undefined. (line 4, file "Code")
I have been looking into e.parameter object, but have not been able to make any headway
function doGet(e) {
Logger.log(e)
var passedString,whatToReturn;
passedString = e.parameter.searchStringName;
if (passedString === 'tylog') {
whatToReturn = tylog(); //Run function One
};
return ContentService.createTextOutput(whatToReturn);
};
var mns = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Monster")
var tyl = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("tyLog")
var tyd = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("tyData")
var twl = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("twLog")
var twd = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("twData")
var tym = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("tyMaster")
var twm = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("twMaster")
var test = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test")
var tydate = tyd.getRange('A2');
var tydur = tyd.getRange(2, 2);
// Start functions
function start() {
tyl.getRange('A1').setValue(new Date());
twl.getRange('A1').setValue(new Date());
}
//Log Typhoon ride
function tylog() {
tyl.getRange(tyl.getLastRow() + 1, 1).setValue(new Date());
}
//Log Twister ride
function twlog() {
twl.getRange(twl.getLastRow() + 1, 1).setValue(new Date());
}
//Send Data to both logs and clear
function tyclear() {
tyd.getRange('A2:H2').copyTo(tym.getRange(tym.getLastRow() + 1, 1), {contentsOnly: true});
twd.getRange('A2:H2').copyTo(twm.getRange(twm.getLastRow() + 1, 1), {contentsOnly: true});
tyl.getRange('A1:A100').clearContent();
twl.getRange('A1:A100').clearContent();
}
URL Request:
https://script.google.com/macros/s/AKfycbxC5zYevR1IhfFcUMjmIqUaQ1dKNHTm4mhmWBq_Rc9HgemJQ6Q/exec?searchStringName=tylog
I put this into a new project by itself and it still returned undefined​.
function doGet(e) {
var passedString,whatToReturn;
passedString = e.parameter.searchStringName;
if (passedString === 'functionOne') {
whatToReturn = functionOne(); //Run function One
};
return ContentService.createTextOutput(whatToReturn);
};
function functionOne() {
var something;
return ContentService.createTextOutput("Hello, world!"); }
I believe that your URL should be https://script.google.com/macros/s/AKfycbxC5zYevR1IhfFcUMjmIqUaQ1dKNHTm4mhmWBq_Rc9HgemJQ6Q/exec?searchStringName=functionOne
After pondering this question for a while it makes no sense to require a return from functionOne. I was getting the client server communication mixed up with the Get request process. For most Get requests the request suggests some type of response since in general we're looking for some type of content to be displayed. In this situation that may not be required since the requestor is a machine.
The use of e.parameter.paramname; just enables us to send key/value pairs from within our querystring that we can recover to redirect our server actions.
2020 UPD:
Upon revisiting the question, I noticed that the OP runs the doGet trigger in the context of script editor, hence the e becoming undefined (as it is only constructed when a request hits the URL with an HTTP request with GET method).
Thus, the answer to the debugging part is:
When running a trigger manually from the script editor, event object will be unavailable
The answer to the running part is as a result of an extended discussion:
When assigning a result of the function, one has to put the return statement inside the function, and the tylog function did not return anything.
Also note that any change to a Web App code, unless accessing it via /dev endpoint (i.e. via /exec endpoint), won't be available until after redeployment.
References
Web Apps guide

Using google.visualization.Query in google web app

I have a functioning google web app that is identical to the app presented [here]
You'll note in code.gs that SpreadsheetApp.openByID......getRange().getValues() is used to retrieve an Array that is later converted into a DataTable in the Dashboard-JavaScript.html
Working Code.gs:
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
// Build and return HTML in IFRAME sandbox mode.
return template.evaluate()
.setTitle('Dashboard demo')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
/**
* Return all data from first spreadsheet as an array. Can be used
* via google.script.run to get data without requiring publication
* of spreadsheet.
* Returns null if spreadsheet does not contain more than one row.
*/
function getSpreadsheetData() {
var sheetId = '-key-';
var data = SpreadsheetApp.openById(sheetId).getSheets()[0].getRange("A1:D8").getValues();
return (data.length > 1) ? data : null;
}
I would like to use google.visualization.query instead of .getRange.
Does not work - currently returns "Google" not defined
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
// Build and return HTML in IFRAME sandbox mode.
return template.evaluate()
.setTitle('Dashboard demo')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSpreadsheetData() {
var opts = {sendMethod: 'auto'};
var sheetId = '-key-';
var query = new google.visualization.Query('http://spreadsheets.google.com?key=' + sheetId, opts);
query.setQuery('select A, B, C, D');
query.send(draw)
}
function draw(response) {
if (response.isError()) {
alert('Error in query');
}
alert('No error')
}
I'm certain there are several issues - but I can't get any helpful errors returned to debug the issue.
My questions are:
Is is possible to use google.visualization.query in code.gs?
(I've read a post that leads me to believe that perhaps it cannot be used server side??/why)
If yes - how do I avoid "google not defined" errors
If no - is there an alternative method to "query" a google sheet from server side (the end goal is to have the flexibility to omit columns, perform aggregate functions, etc. when the datatable is retrieved). It is not possible to change the underlying spreadsheet (ie. sharing and publishing)
Finally- I apologize if any of this is formatted poorly or not clear. This is my first post here. In addition, I have limited experience and less expertise with javascript/apps script and google web apps.
No, it cannot be done server side, because google is a client side API.
Same reason as with google.script.run. (For a better understanding, you can check the whole code yourself, it resides here, a code that needs to be embedded within <script> tags, on the Html side).
As an alternative for the server side, you should be able to use the URLFetchApp.
The URL to compose should look something like:
var BASE_URL = "https://docs.google.com/a/google.com/spreadsheets/d/";
var SS_KEY = "stringSS_Key";
var BASE_QUERY = "/gviz/tq?tq=";
var partialUrl = BASE_URL + SS_KEY + BASE_QUERY;
var queryToRun = 'select dept, sum(salary) group by dept';
var finalUrl = partialUrl + encodeURIComponent(queryToRun);
And call URLFetchApp.fetch on it.

Google Picker - Return the File ID to my Google Script

I have a fairly basic spreadsheet that uses some Google Scripts to accomplish various tasks. I was trying to cleanup the interface for the end user, and decided to implement the Google Picker. Originally the user had to manually import a CSV into the spreadsheet. The new goal here is to select the CSV via the Google Picker, upload it, import it, then delete it. I already have all the code working to import it and delete it. I just worked up the code for the picker, and it seems to work fine. However, and I think I'm just missing something small, how do I pass the File ID back from the Picker.html to my Google Scripts in order to continue my process?
If it helps, I'm using the basic callback provided in the Google documentation right now. I'm assuming this is where the change will be made. Just not sure what to do.
function pickerCallback(data) {
var action = data[google.picker.Response.ACTION];
if (action == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var id = doc[google.picker.Document.ID];
var url = doc[google.picker.Document.URL];
var title = doc[google.picker.Document.NAME];
document.getElementById('result').innerHTML =
'<b>You chose:</b><br>Name: ' + title + '<br>ID: ' + id;
} else if (action == google.picker.Action.CANCEL) {
document.getElementById('result').innerHTML = 'Picker canceled.';
}
}
This should probably work:
In your pickerCallback(data) function:
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
google.script.run
.withSuccessHandler(useData) // this will call the google apps script function in your Code.gs file
.doSomething(fileId); // this is a function in your JavaScript section where you will do something with the code you got from your apps script function
}
function useData(data) {
// do something with the data
}
In Code.gs, create a function to handle the input from the picker:
function doSomething(fileId) {
// do an operation in Drive with the fileId
var file = DriveApp.getFileById(fileId);
var fileName = file.getName();
return fileName;
}
First of all, open the chrome developer console when you are running this so you can see any errors that happen client side (when the picker is active). You can also use console.log to report any variable values in the Chrome console.
secondly, the call to the server works asynchronously, so it means that in your code, you'll get your message 'script was run', when it fact it hasn't yet. All that's happened is that google.script.run has asked for your server side function to execute.
That's why you have withSuccessHandler and withFailureHandler.
so you should do
google.script.run
.withSuccessHandler (function (response) {
document.getElementById('result').innerHTML = 'it worked'
})
.withFailureHandler (function (err) {
document.getElementById('result').innerHTML = err;
})
.justatest (fileId);
and back in the server script
function justatest(fileId) {
Logger.log (fileId);
}
If you then go back and look in the script log file, you should see the fileId.