function won't run when executed from htmlService? - javascript

Im trying to switch my current sheet after 5s of the htmlService modalDialog opening.
For some reason SwitchToSheet1() does not work...
.gs
function openModal() {
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createTemplateFromFile('BarcodeLoadingHTML')
.evaluate()
.setWidth(400)
.setHeight(250);
ui.showModalDialog(html, "‎");
}
function SwitchToSheet1() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Bestandsliste'), true);
};
BarcodeLoadingHTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('jQuery'); ?>
<?!= include('Stylesheet'); ?>
<?!= include('lottieplayer'); ?>
</head>
<body>
<div id="loading">
<lottie-player id="lottie-load" src="https://static.staticsave.com/lottie/cloudupload.json"
background="transparent"
speed="1"
loop
autoplay>
</lottie-player>
<lottie-player id="lottie-success" src="https://assets3.lottiefiles.com/private_files/lf30_qXYuJE.json"
background="transparent"
speed="1">
</lottie-player>
<p class="loadingtext" id="text">Bitte warten<span>.</span><span>.</span><span>.</span></p>
</div>
<script>
$(window).ready(setTimeout (function() {
$('#lottie-load').hide()
$('#text').text('Upload Erfolgreich!')
$('#lottie-success').fadeIn()
$('#lottie-success').get(0).play();
}, 2500));
$(window).ready(setTimeout (function() {
google.script.run.SwitchToSheet1();
google.script.host.close();
}, 5000));
</script>
</body>
</html>

Replace
google.script.run.SwitchToSheet1();
google.script.host.close();
by
google.script.run
.withSuccessHandler(() => google.script.host.close())
.SwitchToSheet1();
The above because google.script.host.close() is executing before google.script.run.SwitchToSheet1(). This happens because calls to server code using google.script.run are asynchronous, in other words, the Google servers not all the time responds instantly when they are called by run, so google.script retry until the server responds, but if the dialog is closed, there aren't more attempts to call the server.
Related
Auto close modal dialog - After server code is done, close dialog in Google Spreadsheet
Modal dialog doesn't write back to sheet, when google.script.host.close() is used

FWIW, assuming I have a spreadsheet with two sheets named Sheet1 and Sheet2, and Sheet2 is the active, the following code works for me:
// Code.gs
function showDialog() {
const html = HtmlService.createHtmlOutputFromFile('page')
.setWidth(400)
.setHeight(400);
SpreadsheetApp.getUi().showModalDialog(html, 'My custom dialog');
}
function SwitchToSheet1() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sh = spreadsheet.getSheetByName('Sheet1');
spreadsheet.setActiveSheet(sh, true);
};
And the HTML page:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
window.addEventListener('DOMContentLoaded', () => {
setTimeout (function() {
google.script.run.SwitchToSheet1();
google.script.host.close();
}, 5000)
})
</script>
</body>
</html>

Related

what is the error in this web app script to give the desired effect?

enter image description herewe've tried to write a script for a web app to a specific spreadsheet
the code is 2 files one in js
function doGet() {
return HtmlService.createHtmlOutputFromFile("page");
}
//function userClicked(name) {
//var url = "https://docs.google.com/spreadsheets/d/1T3AX_YBC8703g6N7sKot41tXUh6XN4zpcBF2V-_7iJ8/edit#gid=0";
//var ss = SpreadsheetApp.openByUrl(url);
//var ws = ss.getSheetByName("Data");
//ws.appendRow([name])
//Logger.log(name + "Clicked Run Button");
//}
function userClicked() {
Logger.log("Someone Clicked the button");
}
and the other in html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Welcome</h1>
<button id="btn">RUN !!</button>
<script>
function doSomething() {
google.script.run.code.userClicked();
}
document.getElementById("btn").addEventListener("click", doSomething());
</script>
</body>
</html>
we can't get the desired action when run button is clicked
we don't know if it's the declaration of functions or summoning them
please help guide to rectify the error
this is yje project link for further analysis
https://script.google.com/d/1daP7bLBlL46av4Wc6-Pr9-z9lg6JyMY44FUtfA08fnKRKLeMuCTxH3LY/edit?usp=sharing
According to the Google Script client side API documentation, the path to call the App Script function is google.script.run.yourFunction() so in your html file. Also you are invoking the function straight away and passing the result of it to addEventListener(), instead of passing the function itself. The script should be this:
function doSomething() {
google.script.run.userClicked();
}
document.getElementById("btn").addEventListener("click", doSomething);

Why is the html script not getting the list from my code.gs file

I am working on a youtube sort of thingy but I've been testing it and it doesn't paste the youtube titles into the custom dialog. I have 2 files. Code.gs and youtube.html. Here are the files
Code.gs
function youtube(input1){
const list = []
const sr = YouTube.Search.list("snippet", {q: input1, maxResults: 50})
sr.items.forEach(function(vid){
list.push(vid.snippet.title)
})
return list
}
youtube.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button onclick="printData()">Return</button>
<script>
function printData(){
const list = google.script.run.youtube("test")
document.write(list)
}
</script>
</body>
</html>
When I run it, it just does nothing when I click the button
<script>
function printData(){
const list = google.script.run
.withSuccessHandler((list) => document.write(list))
.youtube("test")
}
</script>
success handler

How to create an HTML template inside a called HTML Template

So, i've been experimenting with de google apps script lately. So far so good, but i ran into a problem that's drivin me out: I have a button in a spreadsheet that calls a sidebar menu with a function in scripts
macros.gs
function sbCases() {
var Form = HtmlService.createTemplateFromFile("Cases");
var ShowForm = Form.evaluate();
ShowForm.setTitle("ASS-CAD - Cases manager system").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showSidebar(ShowForm);
the html file I call with this function works just fine, but I'd like to call a second form, also trough an html file to manage the spreadsheet data. So i've added this function to the .gs file (and started a new html file):
function NovoCasoMSE(){
var Form = HtmlService.createTemplateFromFile("NewCase");
var ShowForm = Form.evaluate();
ShowForm.setTitle("New Case").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showModalDialog(ShowForm, "New Case");
}
but when I try to call it from a button in the first html file, nothing happens at clicking the button (checked the log and the function the button should call isn't being executed.
Follow the code (the html is full of stuff, like the buttons and everything)("btn" is the ID for a button working on the html file):
<script>
document.getElementById("btn").addEventListener("click", NewCase);
function NewCase(){
google.script.run.NewCase()
}
</script>
I'm learning c in college but have very little experience in javascript ou google script, so I'm pretty sure I've done something really wrong. Thanks for any help in advance. :)
You can try something like this:
Run showTSidebar to get things rolling and then click the button.
ag1.gs:
function loadForm() {
var html='<form><input type="text" name="name1"/><input type="button" value="Click" onClick="process(this.parentNode);" /></form>';
return html;
}
function showTSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createTemplateFromFile('ah4').evaluate());
}
function processForm(obj) {
SpreadsheetApp.getUi().alert('name1: ' + obj.name1);
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
ah4.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('sbresrc') ?>
</head>
<body>
<div id="form"></div>
<input type="button" value="Load Form" onClick="loadForm();" />
<?!= include('ah6') ?>
</body>
</html>
ah6.html:
<script>
function loadForm() {
google.script.run
.withSuccessHandler(function(html){
$('#form').html(html);
$('#form').css('display','block');
})
.loadForm();
}
function process(obj) {
google.script.run.processForm(obj);
}
</script>
sbresrc.html:
<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>
animation:

Open a new window from the apps script add-on menu

I have an add-on where I need to redirect to external URL instead loading with Dialog or Sidebar when the menu is clicked.
I have the sidebar code
function showContactDialog() {
var html = HtmlService.createTemplateFromFile('Website').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setWidth(480).setHeight(380);
SpreadsheetApp.getUi().showModalDialog(html, 'Website');
}
In your HTML you can open a new tab (if your browser supports such a thing) but you can't redirect the page.
In your HTML, you can do something like below:
<script>
function openPage() {
window.open('https://google.com', '_blank');
}
window.onload = openPage;
</script>
In your Website.html place this code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script type="text/javascript">
function opentab(){
window.open(LINK_YOU_WANT_TO_OPEN, '_blank');
}
</script>
</head>
<body onload="opentab()">
</body>
</html>
This works fine for me
function open_new_doc()
{
var html = '<script>google.script.host.close();'+
'window.location.href = "'+open_url+'"</script>';
var html_open = HtmlService.createHtmlOutput(html).setSandboxMode(HtmlService.SandboxMode.IFRAME);
DocumentApp.getUi().showModalDialog(html_open, 'Opening New Window...');
}

how to put a variable into GAS

Hi so i've been trying to code in Jquery javascript html and google apps script and i have gotten part of the app but i can't do the other half which is to take the jquery variable and print it in a google spread sheet. This is what it looks like right now.
GAS:
function doGet() {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle('The Game')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function codefunction() {
Logger.log("In codefunction in codegs");
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1> The Game </h1>
<b><em>Output:</em></b>
<p id="output">
</p>
<input type="text" id="txt_box"/>
<button type="button" id="input_button" class="enjoy-css">Enter</button>
<?!= HtmlService.createHtmlOutputFromFile('javascript').getContent(); ?>
</body>
</html>
Jquery/javascript:
<script>
$(function() {
$('#input_button').bind('click',clickButton);
linkTocodegs();
});
function clickButton() {
var boxContents = $("#txt_box").val();
$("#txt_box").val("");
outputMessage(boxContents);
}
function outputMessage(message) {
var text = $('#output');
var item = $('<p>');
var title = $('<span>').text(message);
title.append(item);
text.append(title);
}
function linkTocodegs() {
console.log("in code gs function link");
google.script.run.withSuccessHandler(outputMessage)
.codefunction();
}
</script>
You need to get the value out of the text box and pass it to the server:
function linkTocodegs() {
var userInput;
userInput = document.getElementById('txt_box').value;
console.log("in code gs function link");
google.script.run.withSuccessHandler(outputMessage)
.codefunction(userInput);
}
Code.gs
function codefunction(receivedValue) {
Logger.log("In codefunction in codegs: " + receivedValue);
var ss,sh;
ss = SpreadsheetApp.getActiveSpreadsheet();
sh = ss.getSheetByName('sheet1');
sh.getRange(1,1,1,1).setValue(receivedValue);
}

Categories