Ignore what I said in the question comments about an explicit return... the successHandler syntax is tricky. You need the NAME of a function, without the brackets. No idea why, but there you go.
Code.gs
Here's a quick example of a sidebar that automatically closes after validating the input form. You can test the error behavior by ignoring the input hint.
/**
* Creates a menu entry in the Google Sheets UI when the document is opened.
*/
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
/**
* Runs when the add-on is installed.
*/
function onInstall(e) {
onOpen(e);
}
/**
* Opens a sidebar in the document containing the add-on's user interface.
*/
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('Sidebar')
.setTitle('Simple');
SpreadsheetApp.getUi().showSidebar(ui);
}
/**
* Validates the new text, and inserts it into spreadsheet if it is acceptable.
*
* @param {string} newText The text with which to replace the current selection.
*/
function insertText(newText) {
if (newText.indexOf('Pizza') == -1) {
SpreadsheetApp.getActiveSheet().getActiveCell().setValue(newText);
}
else {
throw new Error( 'No Pizza allowed!' );
}
return;
}
Sidebar.html
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<div>
<form>
<div>
<label for="new-text">Enter new text:</label>
<input type="text" id="new-text" placeholder="Don't enter 'Pizza'!">
</div>
<br>
<div class="block" id="button-bar">
<button id="insert-text">Insert</button>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
/**
* On document load, assign click handler
*/
$(function() {
$('#insert-text').click(insertText);
});
/**
* Runs a server-side function to validate and enter the entered text.
*/
function insertText() {
this.disabled = true;
$('#error').remove();
google.script.run
.withSuccessHandler(google.script.host.close) // <-- No brackets after function name
.withFailureHandler(
function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
})
.withUserObject(this)
.insertText($('#new-text').val());
}
/**
* Inserts a div that contains an error message after a given element.
*
* @param msg The error message to display.
* @param element The element after which to display the error.
*/
function showError(msg, element) {
var div = $('<div id="error" class="error">' + msg + '</div>');
$(element).after(div);
}
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…