Google Apps Script how to use page name to query google sheet - google-apps-script

I have a simple Google Site setup that runs a Web App that queries a Google Sheet, and returns templated html code with the necessary queried information. I would like to add functionality that allows the Script to query the Sheet using the Page Name from where the Web App is embedded.
So, for example, say my website is: https://sites.google.com/view/SOMESITE
Say it has a few pages such as:
https://sites.google.com/view/SOMESITE/Dave
https://sites.google.com/view/SOMESITE/Rick
What I want to do is embed my web app in each of these sheets, and use the respective page name (i.e. Dave or Rick) as a parameter to refine the query the Web App does.
I have tried this, but the 'page' comes back Null.
var page = SitesApp.getActivePage();
var name = Logger.log(page.getName());
How can I get the page name as a variable to use in my Script/Web App?
UPDATE:
I have revised my approach per the comments. So let's say I have the URL to my WebApp like this:
https://www.somedomain.com/blah/blah?Rick
And this is my Web App Code:
DoGet:
function doGet(e) {
var name = e.queryString
return HtmlService
.createTemplateFromFile('index')
.evaluate();
}
getData
function getData() {
// ...here there is a bunch of code extracting data from my spreadsheet
return [pick, title, artist, name]
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<? var data = getAlbum(); ?>
// ... the rest is a bunch of markup that makes a table of the query results from getData
How to I pass the variable 'name', which should equal "Rick", to my getData function so I can use it when querying my Sheet?

You can pass query parameters to your Web App URL, you can check here what query parameters are and how to use them. For example:
https://www.somedomain.com/blah/blah?name=Rick
With the parameter attribute from the e event object, you can get the object with all the parameters you passed to the get request. You can use these values directly in your code.gs file, for example:
DoGet:
function doGet(e) {
var parameters = e.parameter;
getData(parameters);
return HtmlService
.createTemplateFromFile('index')
.evaluate();
}
getData
function getData(parameters) {
// ...here there is a bunch of code extracting data from my spreadsheet
return [pick, title, artist, name]
}
Finally, if you need to communicate between the HTML file and the code.gs file, you should check out the documentation for it.

I didn't have enough room for this in the comments. But this is what the doGet() might look like:
function doGet(e)
{
//Logger.log('query params: ' + Utilities.jsonStringify(e));
if(e.queryString !=='')
{
switch(e.parameter.mode)
{
case 'page4':
setPage('Page4')
return HtmlService
.createTemplateFromFile('Page4')
.evaluate()
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setTitle("Page4");
break;
case 'page3':
setPage('Page3');
return HtmlService
.createTemplateFromFile('Page3')
.evaluate()
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setTitle("Page3");
break;
case 'page2':
setPage('Page2');
return HtmlService
.createTemplateFromFile('Page2')
.evaluate()
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setTitle("Page2");
break;
case 'page1':
setPage('Page1');
return HtmlService
.createTemplateFromFile('Page1')
.evaluate()
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setTitle("Page1");
break;
default:
setPage('Page1');
return HtmlService
.createTemplateFromFile('Page1')
.evaluate()
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setTitle("Page1");
break;
}
}
else
{
setPage('Page1');
return HtmlService
.createTemplateFromFile('Page1')
.evaluate()
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setTitle("Page1");
}
}
Requirements for WebApps

Related

How To Pass e.parameter to Html Page in Google App Script Web App

I am writing a script take a user from a URL Parameter and number of emails as shown below
enter image description here
However "UserName" is being displayed with Quotes is it possible to stop this code is shown below,
extracts from index.html
<script>
function onSuccess2(jUserName)
{
var div = document.getElementById('output2');
div.innerHTML = 'You User Name Is ' + jUserName
}
google.script.run.withSuccessHandler(onSuccess2)
.getUserName();
</script>
<body>
<div id="output"></div>
<div id="output2"></div>
</body>
code.gs
const userProperties = PropertiesService.getUserProperties();
function doGet(e) {
Logger.log(JSON.stringify(e.parameter));
UserName=JSON.stringify(e.parameter['UserName']);
userProperties.setProperty('UserName', UserName);
Logger.log("UserName= "+UserName);
return HtmlService.createHtmlOutputFromFile('Index');
}
function getUnreadEmails() {
return GmailApp.getInboxUnreadCount();
}
function getUserName() {
Logger.log("Getting User Name");
return userProperties.getProperty("UserName");
}
Modification points:
In your script, getUnreadEmails() is not used.
In your situation, I thought that when an HTML template is used, the script might be simple. And also, when google.script.run is used, it is run after the HTML was loaded. By this, when an HTML template is used, this cost might be able to be reduced.
When these points are reflected in your script, how about the following modification?
HTML side: Index.html
<body>
<div id="output">Count: <?= count ?></div>
<div id="output2">You User Name Is <?= userName ?></div>
</body>
Google Apps Script side: Code.gs
function doGet(e) {
const html = HtmlService.createTemplateFromFile('Index');
html.count = GmailApp.getInboxUnreadCount();
html.userName = e.parameter['UserName'];
return html.evaluate();
}
When this Web Apps is accessed with a URL like https://script.google.com/macros/s/###/exec?UserName=sample, the following result is obtained.
Count: 123
You User Name Is sample
Reference:
HTML Service: Templated HTML

Use Google Web App URL Parameter As Part Of Function

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.

Run multiple scripts when we open an HTML web app

How to run multiple scripts when we open an HTML web app...?
Below is my example script, when user opens the HTML web apps the second (function getMail) script should run and capture the email id in defined sheet
function doGet() {
return HtmlService
.createTemplateFromFile('index')
.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function getMail() {
Logger.log(Session.getActiveUser().getEmail());
var value = Logger.getLog();
var ss = SpreadsheetApp.openById("1IRpIzJKdc50dz99hYHoUVUBuwwhZI4NGdEKbc2QWqS8").getActiveSheet();
ss.getRange(ss.getLastRow()+1,1).setValue(value);
}
function getData() {
return SpreadsheetApp
.openById('1P0Z_njzrwjiPHrynDW37OTjwaPPFvntpiyBYSNBXt40')
.getDataRange()
.getValues();
}
You can call Google Apps Script function getMail from index.html template using next syntax:
<? getMail() ?>
Detailed docs: https://developers.google.com/apps-script/guides/html/templates#calling_apps_script_functions_from_a_template

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.

Apps Script parameters with script.google.run

With Apps Script, it's not allowed to use iframes or AJAX calls. So, I was hoping to restructure my script. Basically, it's just supposed to be a single file chooser.
function doGet(e)
{
return HtmlService.createHtmlOutputFromFile('index');
}
function browse(e)
{
var use_root_folder = typeof(e.parameter.folder_id) == "undefined";
var base_folder;
if(use_root_folder)
{
base_folder = DriveApp.getRootFolder();
}
else
{
base_folder = DriveApp.getFolderById(e.parameter.folder_id);
}
//more code...
}
In sample code on apps script, it looks like I'm supposed to create an html file and put this in it...
<script>
google.script.run.browse();
</script>
Except the "e" argument is only available from within the actual script and not the html file? How would I go about passing a query string parameter from within the HTML file back to the script?
When using google.script.run, you pass variables directly. So you can simply call browser() with the ID of the folder you want.
In the script file:
function browse(folderID)
{
var use_root_folder = typeof(folderID) == "undefined";
var base_folder;
if(use_root_folder)
{
base_folder = DriveApp.getRootFolder();
}
else
{
base_folder = DriveApp.getFolderById(folderID);
}
//more code...
}
And in the HTML file:
<script>
google.script.run.browse(selectedFolderId);
</script>