Google apps script html to spreadsheet - javascript

I am learning google apps script at the moment by myself.
I have been trying to get someone's mail and append it to a google spreadsheets.
My code.gs looks actually like this:
function doGet() {
return HtmlService.createHtmlOutputFromFile("page");
};
function addEmail (mail) {
var mysheet = SpreadsheetApp.openById("1k3vWmg9859mYykNNl0xDWoR_LUhnvLlq1qW8kSRuL_Q").getSheetByName("Sheeet1");
mysheet.appendRow(mail);
};
And my html file looks like this:
<html>
<head>
<base target="_top">
</head>
<body>
<h1>hello</h1>
</body>
<label for="getUserMail">Type your mail here</label> <input type="text" id="getUserMail">
<button id="trigger">Submit!</button>
<script>
document.getElementById("trigger").addEventListener("click",sendMailToCode);
function sendMailToCode () {
var umail = document.getElementById("getUserMail");
google.script.run.addEmail(umail);
};
</script>
</html>
But it doesn't work. I have tried doing multiple stuff to fix it, even adding a tag on html but it does not save the value on the spreadsheet. Could someone please give an advice?

Try this:
This will append the html to the sheet but it will not render it.
function addEmail (mail='<html><head><basetarget="_top"></head><body><h1>hello</h1></body><labelfor="getUserMail">Typeyourmailhere</label><inputtype="text"id="getUserMail"><buttonid="trigger">Submit!</button><script>document.getElementById("trigger").addEventListener("click",sendMailToCode);functionsendMailToCode(){varumail=document.getElementById("getUserMail");google.script.run.addEmail(umail);};</script></html>') {
var ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
sh.appendRow([mail]);
}
appendRow
Reading the description of row contents: "An array of values to insert after the last row in the sheet."

Related

Embed images in the body of an automated email - Apps Script Issue

I am trying to create an automated email with an embedded image. It works on Apps Scripts but when I send the email, I receive the code of my function. So far, I have created an HTML file with the base64 image code (it works), the file with the function and the main code, with the spreadsheets and everything. Does anyone know how to fix it?
Main code:
function inlineImages() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EAD");
var range = sheet.getDataRange();
var values = range.getValues();
var rows = range.getNumRows();
for (var row = 1; row < rows; row++) {
var email = values[row][5];
var name = values[row][4];
MailApp.sendEmail(email, "This is a test", doGet);
}
}
Function HtmlService:
function doGet() {
return HtmlService.createHtmlOutputFromFile('imagem');
}
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<img src="data:image/png;base64, /codeHere" alt="Red dot"/>
</body>
</html>

How can I use the variable in the gs file as the input value in the HTML file in Google Apps script?

The variable fieldName for testGetFieldName function is located at Code.gs
I want to insert it into the input value of the index.html file.
But if I open Sidebar using testSetValue, the value comes out as undefiend.
How can I get the variable 'Account' to come out with Value?
The code I wrote is as follows.
//code.gs
function testGetFieldName(){
var fieldName = 'Account';
return fieldName;
}
function testSetValue(){
var html = HtmlService.createTemplateFromFile('index');
var output = html.evaluate()
.setTitle('MySidebar')
.setWidth(400)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showSidebar(output);
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="text" id ='textValue' name='textValue' value=''/>
<script>
document.getElementById('textValue').setAttribute('value',google.script.run.testGetFieldName());
</script>
</body>
</html>
In your script, how about the following modification?
Google Apps Script side:
From:
var html = HtmlService.createTemplateFromFile('index');
var output = html.evaluate()
To:
var html = HtmlService.createTemplateFromFile('index');
html.value = testGetFieldName();
var output = html.evaluate()
HTML side:
From:
document.getElementById('textValue').setAttribute('value',google.script.run.testGetFieldName());
To:
document.getElementById('textValue').setAttribute('value', '<?= value ?>');
Note:
If you want to use google.script.run, how about the following modification?
From
document.getElementById('textValue').setAttribute('value',google.script.run.testGetFieldName());
To
google.script.run.withSuccessHandler(e => {
document.getElementById('textValue').setAttribute('value', e);
}).testGetFieldName();
Reference:
HTML Service: Templated HTML
In general, it's a best practice to separate your HTML,CSS,JavaScript files.
References
HtmlService Best Practices

Move sheet when drop-down menu is selected

I want to implement a function that moves to the selected sheet when selecting the drop-down menu (sheet name) in Google spreadsheet, but it's not working well.
The menu shows all the seat names, but if you select that particular seat, nothing will happen.
I keep searching and searching, but I don't see a clear solution. What should I do? Please help me.
The code I wrote is as follows.
code.gs
function onOpen() {
createMenu()
}
function createMenu(){
const ui = SpreadsheetApp.getUi()
const menu = ui.createMenu("Sidebar")
menu.addItem("Open Sidebar", "openSidebar");
menu.addToUi()
}
function openSidebar() {
ss = SpreadsheetApp.getActiveSpreadsheet();
var html = HtmlService.createTemplateFromFile('sidebar')
.evaluate()
.setTitle('Salesforce')
.setWidth(400);
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showSidebar(html);
}
sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id = "moveButton" class="button alert">Move</button>
<select name="Available sheets" onchange="moveSheet()" style="width:280px;height:30px;">
<? var sheets=ss.getSheets(); ?>
<? for(var i=0;i<sheets.length;i++) { ?>
<option value=<?=sheets[i].getName()?>> <?= sheets[i].getName()?></option>
<? } ?>
</select>
<script>
function myJsFunction(){
var name = document.getElementsByName("Available sheets")[0].value;
}
function moveSheet(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(name);
if(sheet !=null){
ss.moveActiveSheet(sheet);
}else{
//
}
}
document.getElementById("moveButton").addEventListener("click",moveSheet());
//google.script.run.withSuccessHandler(name);
};
</script>
</body>
</html>
I believe your goal is as follows.
You want to move the sheet by selecting the sheet name from the dropdown list at the sidebar of Spreadsheet.
When I saw your showing script, I thought that you are trying to run the Google Apps Script at the sidebar. At the sidebar and dialog of Spreadsheet, the Javascript is run with the client browser. On the other hand, Google Apps Script is run on the internal server side of Google. I thought that this might be the reason for your issue.
When your showing script is modified for achieving your goal, how about the following modification?
Google Apps Script side: code.gs
In this modification, your function of openSidebar is modified and a new function of moveSheet is added.
Here, in order to move the active sheet, activate() is used.
function moveSheet(e) {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(e).activate();
}
function openSidebar() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var options = ss.getSheets().map(s => {
var sheetName = s.getSheetName();
return `<option value="${sheetName}">${sheetName}</option>`;
}).join("");
var html = HtmlService.createTemplateFromFile('sidebar');
html.options = options;
var h = html.evaluate().setTitle('Salesforce').setWidth(400);
SpreadsheetApp.getUi().showSidebar(h);
}
HTML side: sidebar.html
I modified select tag and removed moveSheet().
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id="moveButton" class="button alert">Move</button>
<select name="Available sheets" onchange="google.script.run.moveSheet(this.value)" style="width:280px;height:30px;">
<?!= options ?>
</select>
<script>
document.getElementById("moveButton").addEventListener("click",moveSheet());
//google.script.run.withSuccessHandler(name);
};
</script>
</body>
</html>
When you run openSidebar, a sidebar is opened. And, you can see the dropdown list including the sheet names. When you change the dropdown list, the active sheet is changed to the sheet of the selected sheet name.
References:
HTML Service: Templated HTML
activate()

Updating or inserting data from a Spreadsheet into a Dialog box inside a dropdown

Goal: The purpose is that a sheet will contain information, this information is placed inside a namedrange, the namedrange will be dynamic (the entire column is given a namedrange).
I created a html popup which contains a dropdown list. This dropdown list must contain the list of information from the namedrange.
I am unable to understand how this is to be done. Here is the code below:
function fncOpenMyDialog() {
var htmlDlg = HtmlService.createHtmlOutputFromFile('HTML_myHtml')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'New File');
};
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
var ui = SpreadsheetApp.getUi();
ui.createMenu('New')
.addItem('New Save File Extension','fncOpenMyDialog')
.addToUi();
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select name="nameYouWant" placeholde="File Type">
<option value="something">Word</option>
<option value="anything">MS Excel</option>
<option value="anything">MS Powerpoint</option>
<option value="anything">MS Slides</option>
</select>
<hr/>
<p>Choose a file, which will then be saved into your Google Drive.</p>
<button onmouseup="closeDia()">Close</button>
<button onmouseup="onOpen()">Save</button>
<script>
window.closeDia = function() {
google.script.host.close();
};
window.saveDia = function() {
onOpen();
};
</script>
</body>
</html>
As you can see in my html file, that the extensions are currently hardcoded.
I am trying to make this dynamic, how do I achieve this?
I believe your goal as follows.
You want to put the values to the dropdown list by retrieving from the named range of the Spreadsheet.
In this case, is the named range the same with this thread?
For this, how about this answer?
Modification points:
From google.script.host.close(), I understood that the HTML file of HTML_myHtml is included in the Google Apps Script project. By this, I would like to propose to achieve your goal using google.script.run.
If the named range is the same with your previous question, you can use it by modifying a little.
When above points are reflected to your script, it becomes as follows.
Modified script:
HTML and JavaScript side: HTML_myHtml
Please modify HTML_myHtml as follows.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="select" name="nameYouWant" placeholde="File Type"></select>
<hr />
<p>Choose a file, which will then be saved into your Google Drive.</p>
<button onmouseup="closeDia()">Close</button>
<button onmouseup="onOpen()">Save</button>
<script>
google.script.run.withSuccessHandler(v => {
const obj = document.getElementById("select");
v.forEach(e => {
const option = document.createElement("option");
option.text = e;
option.value = e;
obj.appendChild(option);
});
}).readNamedRange();
window.closeDia = function() {
google.script.host.close();
};
window.saveDia = function() {
onOpen();
};
</script>
</body>
</html>
Google Apps Script side: Code.gs
At above HTML, readNamedRange() is used. So please put the following script. If you have the same function names, please modify them. In this script, the values are retrieved from the named range of listDown, and sent to HTML side using google.script.run.
function readNamedRange() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var result = activeSheet.getRange("listDown").getValues();
var end = activeSheet.getLastRow();
var values = [];
for (var i = 0; i < end; i++) {
if (result[i][0] != "") {
values.push(result[i][0]);
}
}
return values;
}
Note:
About window.saveDia = function() {onOpen()};, unfortunately, I couldn't understand about what you want to do.
Reference:
Class google.script.run

Create HTML Form & send data to Google-Sheet on submit

I'm new with Google-Sheet and I didn't use Javascript for a few years.
I'm trying to create a form that can write some data in a sheet. My form looks OK. But when I click the submit button, the form disappear and nothing happens on my sheet. My browser display just an blank tab.
For now, I tried to make work a form with a single input but nothing works. I don't see any error msg in my browser...
I have ( my .gs) :
function doGet(request) {
return HtmlService.createHtmlOutputFromFile('HTMLForm');
}
function processForm(form) {
var url = "https://docs.google.com/spreadsheets/d/1dEJEuWmG-4Z2geqz9LroTsIbq6LwMSZgVft5uo5vQxw/edit#gid=0";
var sheet = SpreadsheetApp.openByUrl(url);
var x = sheet.getSheetByName("DATA");
x.appendRow([form.Thing_ID]);
}
And my form :
<!DOCTYPE html>
<html>
<script>
function mySubmit(form) {
google.script.run.processForm(form);
document.getElementById("myForm").reset();
}
</script>
<head>
<base target="_top">
</head>
<body>
<form id="myForm" onsubmit="mySubmit(this)">
<label>Thing's ID</label>
<input type="text" id="Thing_ID" placeholder="ID" required/>
<button type="submit"id="submit">Submit</button>
</form>
</body>
</html>
I need that the value I type in the input is written in my spreadsheet (sheet "DATA"). If you could tell me what function I missed/missused.
Thanks

Categories

Resources