I am using google web app in order to build simply HTML which inserting some informations filled by user to google sheet (apps script application is hosted in a Google Apps Enterprise account). What I'm trying to do is display user e-mail at HTML Page by using Session.getEffectiveUser().getEmail() method. Could you please advise me how can I do it?
This is my code.gs:
function doGet(e) {
return HtmlService.createTemplateFromFile("page.html").evaluate();
}
function userClicked(userInfo){
var url ="path";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("BAZA");
var l_row = ws.getLastRow() + 1
ws.getRange(l_row,1).setValue(userInfo.RANK)
Here is HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("page-css.html"); ?>
</head>
<body>
<div class="row">
<div class="input-field col s2">
<select id="RANK">
<option value="" disabled selected>Wybierz rank </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label>Rank</label>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include("page-js.html"); ?>
**HERE SHOULD BE USER ADDRESS EMAIL**
</body>
</html>
JavaScript code:
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
document.getElementById("btn").addEventListener("click",clickedBtn);
function clickedBtn(){
var responseInfo = {};
responseInfo.RANK = document.getElementById("RANK").value;
google.script.run.userClicked(responseInfo);
}
</script>
Since you are using a template (createTemplateFromFile) you could replace
**HERE SHOULD BE USER ADDRESS EMAIL**
by
<?= Session.getEffectiveUser().getEmail() ?>
In order to this to work, you should set to web application to be executed as the user who is accessing it.
Reference
https://developers.google.com/apps-script/guides/web
Session.getEffectiveUser()
Related
I am trying to make a drop-down box (select), and get the options from a sheet, but I can't get it to work. Actually the problem is, that I have to wait for the script.run to finish, before I add to the select. I therefore moved the add, to the successhandler-function, but somehow it doesn't do anything. If I run it, as this I only get option 1 and 2.
My document look like this:
The server-side code looks like this, stripped down to nothing, just to make sure the miss isn't coming from here.
<!DOCTYPE html>
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta dato="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<div class="row">
<form action="/action_page.php" id="inputform">
<div class="input-field">
<input id="tekst" type="text" class="validate">
<label class="active" for="tekst">Tekst</label>
</div>
<div class="input-field">
<select name="Choose" id="Choose">
<option value="" selected disabled hidden> Choose</option>
</select>
</div>
</form><!--- end form
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
var instance = M.FormSelect.getInstance(elem);
});
var konto = "Choose";
var x = document.getElementById("Choose");
var option = document.createElement("option");
option.text = "Option 1";
x.add(option);
google.script.run.withSuccessHandler(fillOption).getOption();
var option = document.createElement("option");
option.text = "Option 2";
x.add(option);
function fillOption(){
var konto = "Choose";
var x = document.getElementById("Choose");
var option = document.createElement("option");
option.text = "Option 3";
x.add(option);
}
</script>
</body>
</html>
The serverside code looks like this, stripped down to nothing, just to make sure the miss isnt comming from here.
function onOpen() {
var template = HtmlService.createTemplateFromFile("userform");
var html = template.evaluate();
html.setTitle("Just testing select").setHeight(500).setWidth(700);
SpreadsheetApp.getUi().showModelessDialog(html, "testing");
}
function getOption() {
}
I'm working on a project, where the user will use side-bar html page, as a form to update a sheet (very basic operation).
I'm having issue with the autocomplete part.
I'm a beginner to code html with google apps script, so please let me know if you don't have enough information.
The script is supposed to get names from a google sheets, and populate it to the autocomplete item.
I followed a tutorial doing practically the same operation, but based on a web app using a google spreadsheet ==> this one worked perfectly for me.
The challenge is now into adapting it to a sidebar page on google sheet ==> does not work at the moment.
I've been struggling for hours and trying different options, so here is :
- What I made on gs page :
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shEmployees = ss.getSheetByName("Employes");
var colEmploye_nomPrenom=1;
var colEmploye_barcode=colEmploye_nomPrenom+1;
var colEmploye_mail=colEmploye_barcode+1;
var colEmploye_metier=colEmploye_mail+1;
function loadBasicForm(){
var tmp=HtmlService.createTemplateFromFile("basicHtmlForm");
var html = tmp.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
html.setTitle("Test");
SpreadsheetApp.getUi().showSidebar(html);
}//function loadBasicForm(){
function getUnactiveEmployees(){
var ws=shEmployees;
var values= ws.getRange(1,1,ws.getLastRow(),colEmploye_metier).getValues();
var options={};
for (var i=0;i<values.length;i++){
var name=values[i][colEmploye_nomPrenom-1];
var job=values[i][colEmploye_metier-1];
var testUnactive_OK=job=="Désactivé";
if (testUnactive_OK){
options[name]=null;
}//if (testUnactive_OK){
}//for (var i=0;i<values.length;i++){
Logger.log (options);//returns {employee1=null, employee8=null, employee3=null, employee9=null, employee5=null, employee10=null, employee7=null, employee6=null, employee11=null, employee4=null, employee2=null}
return options;
}
What I made on html page :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"><!--Import Google Icon Font-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"><!-- Compiled and minified CSS -->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!--Let browser know website is optimized for mobile-->
</head>
<body>
<div class="container">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input type="text" id="searchedEmployee" class="autocomplete" required><!-- ISSUE AT FILLING IT -->
<label for="searchedEmployee">Spell a Name</label>
</div>
</div><!-- END ROW -->
</div ><!-- END CONTAINER -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <!-- Compiled and minified JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
google.script.run.withSuccessHandler(populateEmployees).getUnactiveEmployees();
});
function populateEmployees(employees){
var autocomplete = document.getElementById('searchedEmployee');
var instances = M.Autocomplete.init(autocomplete, { data:employees });
}
</script>
</body>
</html>
At this point, the side-page is displayed, but nothing is suggested at typing, for example : "emp" for "employeeX" expected with the "getUnactiveEmployees" list.
EDIT :
My issue is not about displaying - that does displaying.
What I cannot do, is to allow the script to autocomplete the item "searchedEmployee". I guess there is an error on this part :
document.addEventListener('DOMContentLoaded', function() {
google.script.run.withSuccessHandler(populateEmployees).getUnactiveEmployees();
});
Do you have any idea of what I did wrong ?
Many thanks !
Try this:
function loadBasicForm(){
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('basicHtmlForm').setTitle('Test'));
}
I want to show that city weather information that I selected from the drop-down, how can I do this through json? I am getting that city through Jquery
when selected I just want to know how can I load the city weather information?
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="weather-container" style="background:#ccc;text-align:center">
<img src="" alt="" class="icon">
<p class="city"></p>
<p class="weather" style="font-size: 22px;margin:0"></p>
<p class="temp" style="font-size: 60px;margin:0;font-weight:bold"></p>
<select name="" class="select_city" id="">
<option value="Lahore">Lahore</option>
<option value="Karachi">Karachi</option>
<option value="Islamabad">Islamabad</option>
<option value="Perth">Perth</option>
<option value="Berlin">Berlin</option>
</select>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
$("select.select_city").change(function(){
var selectedCountry = $(this).children("option:selected").val();
alert("You have selected the country - " + selectedCountry);
});
});
var cityy = "Lahore";
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + selectedCountry + "&units=metric&APPID=d89208ad904d31a4402384ff1d4d1a2f",
function(data){
console.log(data);
var icon = "https://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
$('.icon').attr("src", icon);
var temp = Math.round(data.main.temp);
$('.temp').append(temp);
var weather = data.weather[0].main;
$('.weather').append(weather);
var city = data.name;
$('.city').append(city);
});
You have to use "var selectedCountry" as a global variable so that it should be available to other functions. An issue with scope and context.
Define it like:
var selectedCountry = null;
then in document.ready allocate the value without using var keyword.
selectedCountry = selected values through Javascript
I've been trying to create a new spreadsheet through google script and google spreadsheet and show it to the user. I could create the sheet with SpreadsheetApp.create; however, I couldn't show it on the browser. When I try to search for it in my drive, it is showing up.
I noticed a method show for Sheet, so, I tried that with a single sheet that I created in the newly created Spreadsheet, however, that is not working.
Using GAS, you can't navigate the user to another spreadsheet programmatically.
What you could do is using this show method and present HTML content with a link to the newly created spreadsheet. They'd obviously have to click the link to proceed.
There might be some other things that we can do, but we'd need to know more context as far as what you're trying to accomplish and why.
Create and Show Spreadsheet From a StandAlone WebApp
You could do something like this with a webapp.
Code.gs:
function createSpreadsheet(name){
var file=SpreadsheetApp.create(name);
var sh=file.getActiveSheet();
var fObj={};
sh.appendRow(['FileName:',file.getName()]);
sh.appendRow(['Url:',file.getUrl()]);
sh.appendRow(['Sheet Name:',file.getSheetName()]);
sh.appendRow(['Id:',file.getId()]);
var hl=Utilities.formatString('<a href="%s" target="_blank" >%s</a>', file.getUrl(), file.getName());
fObj['id']=file.getId();
fObj['hl']=hl;
return fObj;
}
function doGet(){
return HtmlService.createTemplateFromFile('creatandshow').evaluate().setTitle('Create and Show Spreadsheet')
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function getFileFolder(Id){
var ss=SpreadsheetApp.openById(Id);
var sh=ss.getActiveSheet();
var file=DriveApp.getFileById(Id);
var folders=file.getParents();
while(folders.hasNext()){
sh.appendRow(['Parent Folder:',folders.next()]);
}
SpreadsheetApp.flush();
}
script.html:
<script>
<script>
function createSpreadsheet(){
var name=$('#ssName').val();
if(!name) {
alert('You did not enter a Spreadsheet Name');
}else{
google.script.run
.withSuccessHandler(function(fObj){
$('#sslinks').html(fObj.hl);
google.script.run.getFileFolder(fObj.id);
})
.createSpreadsheet(name);
}
}
</script>
resources.html:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
creatandshow.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('resources') ?>
<?!= include('css') ?>
<?!= include('script') ?>
</head>
<body>
<div id="sslinks"></div>
<div id="controls">
<input id="ssName" type="text" placeholder="Enter New Spreadsheet Name" size="60" />
<input id="btn1" type="button" value="Create Spreadsheet" onClick="createSpreadsheet();" />
</div>
</body>
</html>
Here's what it looks like:
I am currently making a web page in html with a series of drop down menus. The web site is here: http://tc.met.psu.edu/tcgengifs/index2.html
I am using the following code to make the drop-down menus
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function getUrl() {
var part12 = document.getElementById("firstChoice2").value;
var part22 = document.getElementById("secondChoice2").value;
var part32 = document.getElementById("thirdChoice2").value;
return "http://tc.met.psu.edu/tcgengifs/CMC/"+part12+"/"+part22+part32;
}
function gotoSelection() {
var urlToGoTo = getUrl();
alert(urlToGoTo);
//location.href=urlToGoTo;
function setupLink() {
var urlToGoTo = getUrl();
document.getElementById("gotoLink").href=UrlToGoTo;
}
</script>
</head>
<body onload="setupLink();">
<div id=leftcol>
<select id =firstChoice2 onchange="setupLink();">
<option value=2012072600>2012072600</option>
<option value=2012072512>2012072512</option>
</select>
</div>
<body>
<div id=leftcencol>
<select id =secondChoice2 onchange="setupLink();">
<option value=rain>Rainfall</option>
<option value=slp>Sea Level Pressure</option>
<option value=850virt>850mb Virtual Temperature</option>
</select>
</div>
<div id=rightcencol>
<select id =thirdChoice2 onchange="setupLink();">
<option value=.anim.html>Animation</option>
<option value=0.png>000hr</option>
<option value=1.png>006hr</option>
<option value=2.png>012hr</option>
</select>
</div>
<div id=rightcol>
<a id="gotoLink" href="">Submit</a>
My problem is that I need to use this code (with modifications) multiple times, but when I do that, the submit button for each series of 3 dropdown menus takes me to the site that the last piece of code is designed to take me to. How do I separate the code so that the first series of three dropdowns is not influenced by any other series?
Your second function gotoSelection() is missing a closing brace but that is not what is causing your problems.
The way you are passing the URL back into the anchor isn't correct try;
document.getElementById("gotoLink").setAttribute("href",urlToGoTo);
In your setupLink() function to replace the line;
document.getElementById("gotoLink").href=UrlToGoTo;