how to do to join the adress mail with "mailto", in javascript? - html

Using google app script, the adresse mail filled in the variable , from google sheet API and then, I want to join "mailto:" with the variable of adress mail . This allows to appear this variable in html .
How to do it ?
in google app script:
var Email_user = Session.getActiveUser().getEmail();
var hrefmail = "mailto:"+Email_user ;
var val_htm_mail_1 =hrefmail ;
:
:
:
theHTML.linkEmail = val_htm_mail_1; ( this is to fill the variable "val_htm_mail_1" to send it to HTML
in html :
<span id="linkEmail"><?=linkEmail?></span><br />
thank you in advance for this helpness

I recommend using HTML DOM Edit HTML content instead of a scriptlet. Here's the w3 reference so you can try to write it yourself, instead of just copying mine. Here is an example program:
code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
function include(filename) {
var Email_user = Session.getActiveUser().getEmail();
var hrefmail = "mailto:"+Email_user ;
val_htm_mail_1 = hrefmail ;
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<span id="linkEmail">...</span><br/>
<script>
document.getElementById("linkEmail").innerHTML = this.val_htm_mail_1;
</script>
<?!= include ('javascript'); ?>
</body>
</html>
javascript.html
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
*Note you may need to adjust this depending on your browser settings

Related

Google Apps Script, Google Sheet - Template Scriplets don't work [duplicate]

This question already has answers here:
Adding a property to an Html template gives error "Object does not allow properties to be added or changed"
(2 answers)
Updating content in a Google Apps Script sidebar without reloading the sidebar
(1 answer)
I am trying to pass a variable from my Google Script through to HtmlOutputFromFile
(1 answer)
Closed 8 months ago.
I've been reading these answers and trying out some of the code, but I could not get my code to work. These are the links I've been reading:
https://developers.google.com/apps-script/guides/dialogs#page.html_1
How to pass a parameter to html?
Adding a property to an Html template gives error "Object does not allow properties to be added or changed"
My Code.gs:
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.createMenu('Custom Menu')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setTitle('My custom sidebar');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showSidebar(html);
}
function testCSV2() {
const text = SpreadsheetApp.getActiveSheet().getDataRange().getDisplayValues();
const result = cellArraysToCsv(text);
Logger.log(result);
return result;
}
function cellArraysToCsv(data) {
const regex = /"/g;
let change = data.map(row => row.map(value => `"${value.replace(regex, '\"\"')}"`)).join('\n');
return change;
}
My Page.html:
<!DOCTYPE html>
<script>
function answers() {
var data = google.script.run.testCSV2();
document.getElementById("myTitle").innerText = data;
}
</script>
<html>
<head>
<base target="_top">
</head>
<body>
Hello, world! <input type="button" value="Answers" onclick="answers()" />
<H2 id="myTitle"></H2><br><br>
<?!= testCSV2() ?>
</body>
</html>
I'm getting very confused. Why is it that when I click on the button "Answers", I get no output? And why is <?!= testCSV2() ?> unchanged in the <body> of Page.html?
Description
There are two part to this. Using templated HTML in which testCSV2() is run on the server as well as passing data before the HTML is displayed and using google.script.run.testCSV3() to get data from the server.
Code.gs
function onOpen() {
var menu = SpreadsheetApp.getUi().createMenu("Test");
menu.addItem("Show Test", "showSidebar").addToUi();
}
function showSidebar() {
var html = HtmlService.createTemplateFromFile("HTML_Test");
html.data = "greetings";
html = html.evaluate();
SpreadsheetApp.getUi().showSidebar(html);
}
function testCSV2() {
return "hello";
}
function testCSV3() {
return "goodbye";
}
HTML_Test
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Hello, world! <input type="button" value="Answers" onclick="answers()" />
<H2 id="myTitle"></H2><br><br>
<?!= data ?><br>
<?!= testCSV2() ?>
<script>
function answers() {
google.script.run.withSuccessHandler(
function (data) {
document.getElementById("myTitle").innerText = data;
}
).testCSV3();
}
</script>
</body>
</html>
References
Templated HTML
google.script.run
google.script.run.yourfunctionName();
Use this code in JavaScript to call your function that's defined in gs file.
Reference: Communicate with server function

Apps-script function with dynamic parameter

I am testing the app script platform and I have a doubt when using this code called from HTML file:
JSON.parse(<?= JSON.stringify(getDataFromSheet("tyreUse", "valueSearched")); ?>);
If I set the string value directly it works.
If I try to pass a variable that is declared in it does not recognize it. How can I pass a JS variable to the app script function like next example?
let value_searched = "cars";
JSON.parse(<?= JSON.stringify(getDataFromSheet("tyreUse", value_searched)); ?>);
Scriptlets like <?= ?> are used in html templates to load data from the server into html pages prior to rendering. If you want to pass data back to a server side function then you can use google.script.run and there are restrictions on the data types that you can pass.
google.script.run
Here is an example of getting data from spreadsheet dynamically. I typically build my page and then use an anonymous function of the form (function () {}()); to get the data from spreadsheet and populate the HTML elements with the values.
Create an HTML file HTML_Demo:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="A8SBwf" type="text">
<input id="gNO89b" type="button" value="Click Me" onclick="buttonOnClick()">
<script>
function buttonOnClick() {
try {
google.script.run.withSuccessHandler(
function(response) {
document.getElementById("A8SBwf").value = response;
}
).getCellA1();
}
catch(err) {
alert(err);
}
}
</script>
</body>
</html>
Then in Code.gs create the getCellA1:
function getCellA1() {
try {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange("A1");
return range.getValue();
}
catch(err) {
return err.message;
}
}

Google App Script: how to display google drive files with links to templated HTML

I'm new in both Google App Scripting and JavaScript. So, I'm trying to display the grabbed files from my Google Drive with links however when running displayData(); it's literally showing the link and the title of the file on the page without the actual link in it. Here's picture of the html
output.
Here's what I have so far:
Code.gs
function doGet() {
var output = HtmlService.createTemplateFromFile('Page').evaluate();
return output;
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function displayData() {
var dir = 'Somefoldername';
var foldername = DriveApp.getFoldersByName(dir).next();
var foldercont = foldername.getFiles();
var listicon = '<img src="https://drive-thirdparty.googleusercontent.com/16/type/application/vnd.google-apps.document">';
var file, title, links, list = [];
while (contents.hasNext()) {
file = foldercont.next();
title = file.getName();
links = file.getUrl();
date = file.getDateCreated();
list.push('<tr><td>' + listicon + '<a href ="' + links + '">' + title +'</td></tr>');
}
return list;
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('Stylesheet'); ?>
</head>
<body>
<div class="doclist">
<?= displayData(); ?>
</div>
</body>
</html>
How would I display the Google Drive file hyperlinks in the html template?
Thank you.
Here is a Sample Code:
Note:
I temporarily removed <?!= include('Stylesheet'); ?> in the html file since it is not defined.
Code.gs
function doGet() {
var output = HtmlService.createTemplateFromFile('Page').evaluate();
return output;
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function displayData() {
var dir = 'Somefoldername';
var foldername = DriveApp.getFoldersByName(dir).next();
var foldercont = foldername.getFiles();
var listicon = '<img src="https://drive-thirdparty.googleusercontent.com/16/type/application/vnd.google-apps.document">';
var file, title, links, list = [];
while (foldercont.hasNext()) {
file = foldercont.next();
title = file.getName();
links = file.getUrl();
date = file.getDateCreated();
list.push('<tr><td>' + listicon + '<a href ="' + links + '">' + title +'</td></tr>');
}
return list.join(' ');
}
Modifications done:
Replace while (contents.hasNext()) with while (foldercont.hasNext())
Combine your array list into a single string using array.join(' ') with spaces as its separator
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
google.script.run.withSuccessHandler(function(tblStr){
document.getElementById('FileList').innerHTML = tblStr;
}).displayData();
</script>
<table id="FileList">
</table>
</body>
</html>
Modifications done:
I added a table in the html body with the id "FileList"
I called the server-side function displayData() using google.script.run.withSuccessHandler(function).displayData(). The return value of displayData() will be passed to the callback function's first parameter.
I updated the table's content based on the displayData()'s return value using this procedure document.getElementById('FileList').innerHTML = tblStr;
Output:
Some observations:
The function is returning an array list = [], and you are pushing data into that array.
Your HTML in the screenshot has stray commas in it between each item: ...</td></tr>,<tr><td>....
You shouldn't place a <div> inside a table.
Both of these suggest that you should be appending your data to a string variable, instead of pushing data into an array.
Then return that string from your function, instead of the array.
The string variable will contain the entire contents of your HTML rows and columns.
For the <div>, remove it and place the class in the body:
<body class="doclist">
Depending on how your CSS is set up, that may need modifying to accommodate this change.
Final suggestion: take the resulting HTML which is generated and run it through a validator - for example: https://validator.w3.org/#validate_by_input
That may find some additional issues which need correcting.

Active user's details in the HTML page

How can I print the active user's details in the HTML page? I am able to print in logs and as well as in sheet but not able to print in HTML
<script>
var email = Session.getActiveUser().getEmail();
Logger.log(email);
}
</script>
<p email="email"></p>
Not completely sure what your asking but here's a simple example of getting current user email on to an html dialog. You could deploy it as a web app if you wish.
Code.gs:
function onOpen(e)//for Menu
{
SpreadsheetApp.getUi().createMenu('My Tools')
.addItem('Display Email','displayEmail')
.addToUi();
}
function getCurrentUserEmail()
{
var email={'email':Session.getActiveUser().getEmail()};//returned as an object
return email;
}
function displayEmail()
{
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('getemailinhtml'), 'User Email');//modeless dialog
}
getemailinhtml.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run
.withSuccessHandler(dispEmail)
.getCurrentUserEmail();
});//runs after dom is loaded
function dispEmail(data)
{
$('#email').text(data.email);//put's email into h1 tag
}
console.log('My Code');
</script>
</head>
<body>
<h1 id="email"></h1>//Email show up here
</body>
</html>
To have your script display HTML pages, start with
HTML Service: Create and Serve HTML. A minimal example:
function doGet() {
var email = Session.getActiveUser().getEmail();
var html = '<html><body>Email: ' + email + '</body></html>';
return HtmlService.createHtmlOutput(html);
}
Go to "Publish > Deploy as web app" and set appropriate options, so that the app will run as the user accessing it (who will have to authorize it):
Note that the above example is only suitable as a demo; for larger pages you will want to use templated HTML and other web-oriented features of Google Apps script.

Automated download of file from Drive in Web App?

I'm trying to write a polling web app that checks Google Drive and automatically downloads files without user interaction.
Using ContentService I have managed to get things working when I place the code in the doGet function.
However this only works once and there does not appear to be a way to refresh or reload the page automatically on a timer event.
Using a SetTimeout on the client side javascript I can get a function on the server side to automatically trigger at certain intervals but then I am stuck with what to do with the output from ContentService.
The on Success call back will not accept the output from createTextOutput.
My solution does not not need to be deployed and I'm happy to execute from the editor if that expands my choices.
So once I have the output from createTextOutput on my server side what am I supposed to do with it to get it back to the client in order to cause the file download?
I have included the code if that helps.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
setTimeout(
function ()
{
document.getElementById('results').innerHTML = 'Event Timer';
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.fetchFromGoogleDrive();
}, 60000);
function onSuccess(sHTML)
{
document.getElementById('results').innerHTML = 'File Downloaded ' + sHTML;
}
function onFailure(error)
{
document.getElementById('results').innerHTML = error.message;
}
</script>
</head>
<body>
<div id="results">Waiting to DownLoad!</div>
id="Fetch">Fetch!</button>
</body>
</html>
function doGet() {
Logger.log('doGet');
return HtmlService.createHtmlOutputFromFile('form.html');
}
function fetchFromGoogleDrive() {
//Logger.Log('fetchFromGoogleDrive');
var fileslist = DriveApp.searchFiles("Title contains 'Expected File'");
if (fileslist.hasNext()) {
//Logger.Log('File found');
var afile = fileslist.next();
var aname = afile.getName();
var acontent = afile.getAs('text/plain').getDataAsString();
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.CSV);
output.setContent(acontent);
output.downloadAsFile(aname);
return afile.getDownloadUrl();
}
else
{
//Logger.Log('No File Found');
return 'Nothing to download';
}
//Logger.log('All files processed.');
}
EDIT: Different answer after clarification.
If this is intended to run automated as a webapp what I would do is return the getDownloadUrl and create a new iFrame using that that as the source.
Apps Script
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function getDownloadLink(){
//slice removes last parameter gd=true. This needs to be removed. slice is a hack you should do something better
return DriveApp.getFileById("0B_j9_-NbJQQDckwxMHBzeVVuMHc").getDownloadUrl().slice(0,-8);
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<p id="dlBox"></p>
</body>
<script>
function buildLink(res){
var dlBox = document.createElement("iframe");
dlBox.src = res;
document.getElementById("dlBox").appendChild(dlBox)
}
//automate this as you need
google.script.run
.withSuccessHandler(buildLink)
.getDownloadLink();
</script>
</html>