I intend to write a simple Google Apps Script mail merge app, as a bound script, starting from a draft mail from the user. I open a sidebar with a dropdown to select the drafts. When I fetch the drafts onLoad, it works fine, but when I trigger the fetching with a button, the sidebar is cleared without any error being shown in the console.
I stripped the code to a bare minimum to show the problem:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<div class="sidebar">
<form>
<div class="block">
<div class="inline form-group">
<label for="draft">Choose</label>
<select id="draft">
<option disabled selected>One moment please ...</option>
</select>
</div>
</div>
<div class="block" id="button-bar">
<button id="reload">reload</button>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(function() {
getDrafts();
$('#reload').click(getDrafts);
});
function getDrafts() {
google.script.run
.withSuccessHandler(loadDrafts)
.withFailureHandler(showError)
.getDraftMessages();
}
function loadDrafts(drafts) {
$('#draft').find('option').remove();
for (var i = 0; i < drafts.length; i++) {
$('#draft').append('<option value="' + drafts[i].id + '">' + drafts[i].subject + '</option>');
}
}
function showError(msg, element) {
var div = $('<div id="error" class="error">' + msg + '</div>');
$(element).after(div);
}
</script>
</body>
</html>
The back end javascript (the .gs file) is:
function onOpen() {
var ss = SpreadsheetApp.getActive();
var menu = [{
name: 'Mailmerge tests',
functionName: 'mailMerge'
}, ];
ss.addMenu('MM experiment', menu);
}
mailMerge = function() {
var html = HtmlService.createHtmlOutputFromFile('MailMergeUI').setTitle('Mail merge');
SpreadsheetApp.getUi().showSidebar(html);
}
function getDraftMessages() {
try {
draftMessages = GmailApp.getDraftMessages();
drafts = [];
for (var i = 0; i < draftMessages.length; i++) {
drafts.push({
'id': draftMessages[i].getId(),
'subject': draftMessages[i].getSubject()
})
}
} catch (err) {
throw (err);
}
Logger.log("Returning: ");
Logger.log(drafts);
return drafts;
}
The Logger logs the correct drafts, but the .withSuccessHandler(loadDrafts) in the sidebar is not executed; instead, the sidebar freezes.
In the Chrome developer tools I cannot find the scripts to debug them.