Can't run function from sidebar [duplicate] - google-apps-script

This question already has answers here:
Google Apps Script PERMISSION_DENIED with sheets addon
(2 answers)
Closed 1 year ago.
I'm having problems calling a server-side Apps Script function from a html sidebar in Google Sheets.
I've replicated my issue with the simple example code below.
What it should do
Clicking the button should call alert in my Code.gs script and display an alert to the user.
What actually happens
Clicking the button shows the error:
We're sorry, a server error occurred while reading from storage. Error code PERMISSION_DENIED.
There are no entries in the 'executions' section of the Apps Script dashboard for alert(), so it seems like the function never even gets called?
Code.gs:
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Matthew')
.addItem('Show Sidebar', 'sidebar')
.addToUi();
};
function sidebar() {
const html = HtmlService.createHtmlOutputFromFile('test.html')
.setTitle('Matthew Experiment')
.setWidth(300);
SpreadsheetApp.getUi().showSidebar(html);
}
function alert() {
SpreadsheetApp.getUi().alert("alert!");
}
test.html (well the body)
<body>
<div class="container">
<button class="btn btn-success" onclick="doSomething()">Click Me!</button>
</div>
<script>
function doSomething() {
google.script.run.withFailureHandler(function(error) {
console.log("error")
console.log(error.message)
}).withSuccessHandler(function(result) {
console.log("done!")
}).alert();
}
</script>
</body>
I've confirmed that the client-code is getting properly inflated with server-side function names, it's just calling the function that doesn't work.
My code seems to be the same as all of the getting started guides, but I don't see anyone else posting about this issue. Hoping someone here has deeper knowledge of the problem than I do.
Update, even weirder
I opened a private window and it worked, so I thought, maybe this is an extension causing problems? But even disabling all extensions doesn't fix it in the main window. I've logged out/in to my google account but still can't get it to work without opening a private browser window.
This problem is consistent across chrome/edge/firefox.

This happens when the global logged in user is different from the owner of script.
Logout all your google account and then re-login with the account you used to created the script. This fixed the issue.

Here's a simple example of a side bar dialog communicating with server
function showMySideBar() {
var html='<input type="button" value="Click Me" onClick="doSomething()" />';
html+='<script>function doSomething(){google.script.run.withSuccessHandler(function(msg){window.alert(msg);}).pleaseHelp();}</script>';
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutput(html));
}
function pleaseHelp() {
return 'What can I do to help?';
}

Related

Problem with google.script.run in custom HTML dialog in G Suite account (but not personal Google account)

To diagnose the problem using google.script.run in a custom HTML dialog, I ran Google’s example script and HTML code for dialog boxes in both my personal and G Suite accounts. Here is Google's example: https://developers.google.com/apps-script/guides/html/communication. The code is shown below.
In my personal account, the code worked perfectly. The custom HTML dialog popped up and the function doSomething created log output.
In my G Suite account, the function doSomething did not run at all. I tried playing with settings, testing as an add-on, publishing to the web, and more, but I could not make the Google's sample code work. I spent an hour on the chat session with Google support.
My guess: I am missing a few authorization and/or settings steps in my G Suite account. Please help! I am new to the G Suite AddOn Marketplace, and would appreciate very specific instructions for next steps. I want to make sure my real script works on my G suite account before submitting it for review. I would like to use custom dialog boxes so that I can collect user input in multiple fields.
Here is a link for a document with screen shot images of my authorization and execution windows. I did NOT get the expected "This app isn't verified" warning in my G Suite account. https://docs.google.com/document/d/1IiXmPE7zB1E-s_Uzzhmc0ggOCkz3qqcy1cqZrezkgSg/edit?usp=sharing
Here is the google script code:
// code.gs
// Use this code for Google Docs, Slides, Forms, or Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('Index');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
function doSomething(){ // I added from second step of example
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Sheet1');
var cell1 = sheet.getRange("A1");
cell1.setValue("did something");
Logger.log("did something")
};
Here is the HTML code for the file Index.html:
<!DOCTYPE html>"
<html>
<head>
<base target="_top">
</head>
<body>
Hello, World!
<script>
google.script.run.doSomething();
</script>
<input type="button" value="Close"
onclick="google.script.host.close()" />
</body>
</html>
Similar question posed by: Google Apps Script - HTML service not working properly only on G-suite accounts
Did your script created in your personal or your GSuite accout? Please consider that Google Chrome capture as global log in, the account (email) that you use to do the first log in. Google don't mind if from this logged account you logged in others accounts: Google still continuing considering as global loggin the first one account you logged in. In this way, try to do the first log in with your GSuite accout; I hope this will solve the issue and you can run from all your accounts.
(thanks for Hujie Wang's replied to question/60438751/ : that helped me undertood this issue and solve it for my project)

HTML Dialog don't close in a shared spreadsheet on Google Scripts

I have a spreadsheet that has a function to call an HTML dialog to choose some dates:
htmlDate = HtmlService.createHtmlOutputFromFile('datePicker')
.setHeight(120)
.setWidth(550);
SpreadsheetApp.getUi().showModalDialog(htmlDate, 'Select the dates for presentation:');
This is the part of the HTML code that defines the actions of buttons in datePicker.html:
<input type="button" onClick="submitForm()" value="OK" />
<input type="button" onClick=google.script.host.close() value="Cancel" />
And this is the part of HTML code that calls my function 'newPresentation':
<script type="text/javascript">
function submitForm() {
google.script.run.newPresentation(document.forms[0]);
Utilities.sleep(1000);
google.script.host.close();
}
</script>
The problem is that: When I run the script, it works perfectly. First, it calls my function 'newPresentation', and then it closes itself, running the rest of the script. In function 'newPresentation' there are other HTML dialogs that are called up.
But, when another user runs the script, this HTML dialog doesn't close itself. Even though it doesn't close itself, the rest of the script is executed normally. I have already shared the spreadsheet with another user, with edit privileges.
Both me and the other user are logged in a Google Account.
Some idea how to fix that problem?
PS.: Sorry for some grammatical errors, but I'm not fluent in english.
Try this:
google.script.run
.withSuccessHandler(function(){google.script.host.close();})
.newPresentation(document.forms[0]);
and put a return at the end of newPresentation();
Another possibility is to try using the dummy dialog described here: https://stackoverflow.com/a/55731456/7215091
I'm not certain of the reason that issue occurs. In all tests that i haved make, i used the same computer, with two windows of Google Chrome (one for each user logged in). I can't resolv the problem.
After that, i have tested in a new computer, with one single user logged in, and the script works perfectly.
Aparently, may be some problem related with some cache in browser, or something. I really don't know.

Google Apps - Script - Side bar OnOpen/OnInstall function

I'm recently having issues with Google Apps Scripting, I have a script which installed domain wide, which is enables users to make some tasks easier with the side-bar menu however from last week side-bar menu is not popping up anymore. Nothing has been changed on the code.
I did some workaround and tried all possible ways - deauthorization \ authorization, deploying the same code with different name, nothing worked except if the user removes it and adds it to the spreadsheet which they work - it's popping up and working only for that sheet and only for one time.
Can you please advise, how to fix this issue?
Here is my OnInstall and OnOpen functions:
function onInstall(e)
{
onOpen(e)
}
function onOpen(e) {
var html = HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('BB KING');
SpreadsheetApp.getUi().showSidebar(html);
}
Thanks in advance.
Edit : Triggers making the side-bar work on simple scripts on spesific spreadsheets, but this method is not working on domain-wide installed add-ons.
It should be possible to add a trigger to run the custom function which shows the SideBar.
I have a function like the following in my code that runs on my domain:
function createOnOpenTrigger()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet();
// Trigger on open
ScriptApp.newTrigger(FunctionToRunOnOpen)
.forSpreadsheet(sheet).onOpen().create();
}
function FunctionToRunOnOpen()
{
var html = HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('BB KING');
SpreadsheetApp.getUi().showSidebar(html);
}
You could then put the createOnOpenTrigger function as an option in your custom menu - to be run only once everytime a copy is made of the entire spreadsheet.

Google Apps script function does not work when implemented via a library

I am right at the beginning of my Google Apps Script programming and I have a real problem that I hope some one can help me with. I spent all yesterday trying to solve this but I am going in circles.
I wrote a script that was bound to a Google Doc. From a custom menu I call a html form where I collect the necessary information.
function initiateInvoice() {
var html = HtmlService.createHtmlOutputFromFile('askQu.html')
.setWidth(800)
.setHeight(500);
DocumentApp.getUi()
.showModalDialog(html, 'Daten Eingabe');
}
This form has a „submit“ button and an "exit" button.
<input class="action" onclick="formSubmit()" type="button" value="Submit" />
<input onclick="google.script.host.close()" type="button" value="Exit" />
The script called when the "submit" button is pressed is
<script type="text/javascript">
function formSubmit() {
google.script.run.getValuesFromForm(document.forms[0]);
google.script.host.close();
}
</script>
The function getValuesFromForm then does the stuff that I need doing. And the html form is closed. The stuff that happens is a few calculations and then replacing place holders with text or numbers. I don't think this is relevant but can supply any code needed as required.
This all works exactly as I had hoped.
But now I have moved all the code and html in to an extra library (except the calling of the custom menu). The form still shows when called via the custom menu but the submit button in the form has no function any more. The "exit" button will still work. I have tried stripping everything out of the function that is called so that it does nothing nothing (to be sure it wasn't being called and getting hung up) but this does not help.
I guess that the javascript in the form is not working or not reaching my function getValuesFromForm but I really have no idea where to look or what to do.
I really appreciate any help or tips that any one can give me. Thank you.
Greetings from the Bavarian Alps.
Neill
google.script.run can't run a function from a library, only from a .gs file in the same project.
If you must have your logic code in a library, you will have to create functions in your local .gs file to call the relevant library functions, and these local functions you can invoke with google.script.run

Google App Script WebApp, Manipulating UI

Hi and Good day to all,
Google App Script can be used in so many ways. I know cause I have tried some of them but Iam not an expert so, the situation is.
I have created an Spreadsheet
create a form using the new UI Building that comes with the script editor.
named:gtest01
UI compose of:
label, id=label_caption
button 1, id=button_hide, event-onmouseclick=hide_label
button 2, id=button_show, event-onmouseclick=show_label
button 3, id=button_message, event-onmouseclick=message_me
now, the code is:
/* This is so when I want to just deploy it as a [webapp] using the
script editor -> Publish Deploy as Web App
*/
function doGet(e) {
var app = UiApp.createApplication().setTitle("Sheet Application");
app.add(app.loadComponent("gtest01"));
Logger.log("Application UI Loaded");
return app;
}
function message_me(e) {
Browser.msgBox("my message");
}
function hide_label(e) {
var app = UiApp.getActiveApplication();
label =app.getElementById("label_caption");
label.setVisible(false);
}
function show_label(e) {
var app = UiApp.getActiveApplication();
label =app.getElementById("label_caption");
label.setVisible(true);
}
// this code is for when the spreadsheet is shared so they can access the form
function showform_() {
var app = UiApp.createApplication();
app.add(app.loadComponent("gtest01"));
SpreadsheetApp.getActiveSpreadsheet().show(app);
}
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
menuEntries.push({name: "Show Form", functionName: "showform_"});
ss.addMenu("e-Test", menuEntries);
}
First scenario is that when spreadsheet is shared
when menu is clicked the form will load - thats good
when show and hide button nothing happens - why and how can i fixed
this?
when message button is click - message will show but the form will
close, how can I display a message without closing the form?
Second scenario is that when publish as Webapp.
When Developer Link is Access the UI is always updated - ok
When URL Link is Access the UI is always updated its like it is
cache, how can I fixed this?
on dev link: when show and hide button nothing happens - why and how
can i fixed this?
on dev link: when message button is click - will generate an error,
how can I display an alert message on WebApp
Please help I have search and tried the sample codes and answer in the forum am missing something.
Thanks
Nick Ace
First scenario
when show and hide button nothing happens - why and how can i fixed this?
In your functions, use return app at the end. Unless you return the app object, the UI doesn't get updated.
how can I display a message without closing the form? - Try
SpreadsheetApp.getActiveSpreadsheet().toast()
2nd scenario
When URL Link is Access the UI is always updated its like it is cache, how can I fixed this? - Save your most recent code as a version
on dev link: when show and hide button nothing happens - Again return app will take care of this
on dev link: when message button is click... - Browser.msgBox is not supported in a web app.
When Using UI it is generally a good idea to make everything happen inside this Ui, so try to avoid showing messages with Toast( as they are not supported in web apps anyway).
Since you are using the GUI it should be quite easy to use a label with your message that is initially invisible and to make it visible in an handler routine.
Note that this kind of handler can be a client handler as well unless you need to do something else from this action.
As for the other points of you question, our (very fast) friend Srik has already answered thoroughly ;-)