Click Handler has suddenly stopped working - google-apps-script

I have a script that is both published and been working for months that has suddenly stopped being able to find click handlers (no change to the code).
IE. I get an error like this:
Error encountered: Script function not found: interfaceClass.myClickHandler
"interfaceClass.myClickHandler" does, in fact, exist and it is registered
var indF = app.createCheckBox("Create individual files")
.setName('create')
.setId('createBox');
var chandler = app.createServerHandler('interfaceClass.myClickHandler');
indF.addClickHandler(chandler);
It also doesn't seem to be anything specific to this handler. ALL click handlers are failing.
Given this was working, I'm almost positive this is a result of Google doing an update that broke our code (which they've done in the past). But I need to know what they changed so I can work around it. Does anyone know?

So apparently what they broke is that app.createServerHandler can no longer find functions defined like so:
var obj = {};
obj.method = function (e){
};
You must now use functions declared the following way:
function method(e){
}

Related

TypeError: Cannot read property 'getBody' of null

I'm trying to teach myself to use Google Apps Script, but somehow every function I try returns this error immediately. And since I'm a huge beginner, I don't know what I'm doing wrong.
Here's a simple example of a code I tried to run:
function myFunction(){
//application
//file
var ad = DocumentApp.getActiveDocument();
var docBody = ad.getBody () ;
var paragraphs = docBody.getParagraphs();
//paragraphs[0]. setText ("MY NEW TEXT"):
//var attr = paragraphs[0].getAttributes() ;
//Logger.log(attr);
paragraphs[0].setAttributes({FONT_SIZE:40});
}
Yet no matter what I'm running really, I get this:
TypeError: Cannot read property 'getBody' of null
myFunction # Code.gs:5
What am I doing wrong?
I have an open Google Doc, I've allowed permissions to run the script project. What else should I try? Thanks.
In order to get getActiveDocument() working you need to use it in a script that is container-bound:
Create a new Google Document
Go to Extensions > Apps Script
Run your function inside of it.
If your script is not container-bound, you need to use the openById(id) or openByUrl(url) methods, in order to retrieve a Document
Adblock software was preventing the running somehow. Disabled it and runs fine now. Disregard!

Has my self-invoking workaround worked or is it coincidence?

I've been having an issue with a Google Apps Script I'm running that kept throwing the following error when ever I triggered the code onChange. No such errors were returned when I manually ran the code.
Exception: Service Documents failed while accessing document with id XXXX
The error was happening on the same line of code each time and I've subsequently found that this is a relatively common error and is perhaps happening because my script is quite lengthy and perhaps not as efficient as it should be (I'm very much an Apps Script and JS novice). Interestingly I have a very similar script (with perhaps 20% less variables) running in another file that executes as expected every time.
I had no naming or scoping issues with the variable that was being used to call the document but I thought that perhaps wrapping the troublesome part of the script into a self-invoking function within the larger function would minimise hoisting and improve the efficiency of the script - at least enough to let it run consistently without errors. My understanding of JS is that when a script initiates variable declarations are hoisted within their scope and therefore by creating a self-invoking function I could reduce the hoisting within the main function which contains in excess of 100 variables and therefore reduce the initial demand.
So far the script does appear to be running more quickly and avoiding the error that I'd previously being seeing - the last run was just over 63 seconds whereas the previous successful manual run without the self-invoking function was just under 103 seconds.
I do believe this can be an intermittent error and I'm trying to find a robust, longer term fix without having to rewrite all of my code.
I have detailed the self-invoking code below with any IDs redacted. The part that was causing the error within the script was "var docFinal = DocumentApp.openById(docFinalId);
Do you think this could be a genuine fix or has the code started to work coincidently because of the intermittent nature of this error?
var docTempId = "XXXX";//Template File Id
var docFinalId = "XXXX"; //Final File Id
var sheetId = "XXXX";
(function () { // self-invoked within larger function to minimise hoisting
var docTemp = DocumentApp.openById(docTempId);
var docFinal = DocumentApp.openById(docFinalId);
docFinal.getBody().clear();
var templateParagraphs = docTemp.getBody().getParagraphs();
createMailMerge(Company,Branch,PropertyID,PropertyAddress,ApplicantName,Dateofbirth1,EmailAddress,PhoneNumber,Nationality,PassportNumber,NationalInsuranceNumber,Currentresidentialstatus,LeaseRequested,RentOfferedPCM,TotalNumberofAdultOccupants,Proposedleasecommencementdate1,TotalRentPayers,RentPayer2Name,RentPayer2Phone,RentPayer2Email,RentPayer3Name,RentPayer3Phone,RentPayer3Email,Relationshipwithadultoccupants,Numberofchildren,Ageofchildchildren,Currenteconomicstatus,Applicantoccupation,Applicantemployedorselfemployed,ApplicantDeclaredIncome,SelfEmployedDocuments,EmploymentPartorFullTime,EmploymentContractorPermanent,MainEmploymentCompany,Mainemploymentaddress,Mainemploymentstartdate1,Mainemploymemtpensionpayrollnumber,MainEmploymentManager,ManagerEmail,ManagerPhoneNumber,ApplicantPaymentType,ApplicantHourlyRate,Applicantprimaryaveragehourspermonth,Applicantsalary,ReceivesHousingBenefit,HousingBenefitAmount,Anyadditionalincome,Typeofadditonalincome,Secondemploymentcompany,Rolewithin2ndCompany,ndEmployeraddress,ndEmploymentstartdate1,ndEmployerpensionpayrollnumber,ndEmploymentContact,ndEmploymentEmail,ndEmploymentphonenumber,Additionalincomeamount,Additionalincomedetails,TotalDeclaredGrossIncome,Applicansavingsdeclared,MostRecentAddress,DateStartedlivingincurrentaddress1,Liveanywhereelseinlast3years,Applicant2ndresidingaddress,Applicant2ndaddressmoveindate1,Applicant2ndaddressmoveoutdate1,Applicantadditionaladdressdeclared,Applicantadditionaladdressdetails,Applicantadditonaladdressmoveindate1,Applicantadditionaladdressmoveoutdate1,Applicantpreviouslandlordreference,Landlordreferenceaddress,referencefromlandlordoragent,LandlordAgentName,lengthoftimeatproperty,LandlordAgentphonenumber,LandlordAgentemailaddress,Previouslandlordreferencepreventionreason,Anypets,Petdetails,Applicantsmoke,Applicantsmokeinside,Applicantadversecredit,Adversecreditdetails,Applicantprovidecurrentaccount,Applicantcurrentaccountname,Applicantcurrentaccountbank,Applicantcurrentaccountnumber,Applicantcurrentaccountsortcode,UKbasedguarantor,GuarantorName,GuarantorEmail,GuarantorPhoneNo,Noguarantorreason,NextofKinName,NextofKinrelationship,NextofKinEmail,NoNextofKinPhoneNo,Applicantadditionalinfo,Applicantdocuments,Applicantaccurateinformationdeclaration,Applicantaccepttermsandconditions,submittedatt,Token,maidenname,ApplicantReferencingChoice,Applicantcanprovide,Applicantdocumentlink,ApplicantacceptsHomelet,ApplicantallowsHomelettocontactreferences,ApplicanthappyforHomelet,templateParagraphs,docFinal);
docFinal.saveAndClose();
createPDF(); // calls the next function
}) ();
The script has just failed again. After working on a number of occasions which hadn't been happening, it has now failed and return the same error as before. I can therefore only assume that creating a self-invoking function within the main function has made no material difference to the efficiency of the script.
The error you are receiving does not seem to be the expected one.
I think the best solution in this situation is to file a bug on Google's Issue Tracker by using the template here.

Google Sheets - Script function could not be found

I am working to link an image in my Google Sheet document to a specific cell in another tab. I'm doing this by building a simple function that will do this. However, when I assign the function and then click on the image, I then get the error "Script function "test" could not be found". When I run the function in the script manager interface, it works fine. It's when I try to actually use it in the sheet with the image.
Function Script:
function test()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("TX Marketing Data");
sheet.setActiveRange(sheet.getRange("A91"));
};
Steps to recreate:
1) Create image
2) Go to image, right click, go to drop down and select "Assign Script"
3) Enter "test" as the assign script
Remove ";" at the end of your function (after }).
Had a similar problem and just solved it.
When assigning a script function to a button make sure to call the specific function name(i.e. "getWeatherData") and not the App Script name (i.e. "WeatherAPI").
Another thing that can happen is that you have a library that has the same name as the function. For example you have imported a library that to refer to "test" in your code. If you name your function
function test(){
your code
}
Then you will get the same error that you got.
Try reloading the page.
Sounds like a simple 'turn it off and on again' fix but after having the same issue and trying to save a new version, renaming the function, creating new function etc. a page reload was all it took!
I had exactly the same problem. Eventually I found the problem when I looked at the script Function name, which should be Function followed by the name you gave the script when it was created. when creating file names sometimes you are not able to use special characters which is what I had done. Once I gave it a name that had allowable characters there was no problem. In programming when you call a function that does not match the name given to the function or procedure you will end up getting the error function not found.
I had the exact same issue, when I used submitdata , after I changed it to submitData it said it submitdata was deleted. so i put it back to original form and bam!! fixed.
Same issue, but much dumber reason for me.
So, here is my answer: Make sure to hit the "Save" button in Apps Script.
I was so used to all the other google apps automatically saving/syncing I didn't realize that I actually had to hit "Save" on the scripts. I caught it when I noticed the function I was trying to run wasn't appearing in the list of functions to run in Apps Script. Once it hit save, the name of the function appeared in the list AND clicking my button ran it successfully from the sheet.
You should call your function name, not the script itself. If your function is called myFunction() you should write myFunction. And be careful to rename your function to something that isn't already in your library
Ran into the same issue but solved it by renaming it with a prefix, executing it in Sheets and then renaming it back without the prefix.
function calculateSomething() {
return 10;
}
To
function prefixCalculateSomething() {
return 10;
}
Update the Sheet with the new name, it should work now.
Now rename it back.
function calculateSomething() {
return 10;
}
Update the Sheet with the original name, and it should still work.
Maybe a refresh would've worked as well but that's not how I solved it.
I found that I had renamed my Macro, removed spaces, and added Uppercase, but the name in the script function statement didn't match what I could swear I had set in
"Extensions->Macros->Manage Macros".
When I changed the syntax of the image to match the function statement, including case, it worked fine.
(I don't know if spaces work in the name, I originally had them, but remembered that I've had trouble with them in Excel. I removed them at the same time as doing other changes, so I didn't confirm if it was an issue.)

Basic UiApp failing with error "ReferenceError: "UIApp" is not defined."

I am creating some google app scripts for my company to use to generate random tests for employee training. I already have the basic scripts written to grab a list of questions from a google sheet, randomize them, grab the first 10 questions, etc. That all works fine. I decided it might be better to re-do the whole thing using a UiApp instead of just separate scripts. That is where the problem comes in. I did a simple bare bones UiApp to test with, published it and tried to hit the URL and that's where I encounter this error. I searched for this error and all I could find was some discussion about this being part of google apps premiere(which should have been folded into regular google apps around 2010). I've been staring at this so long I've frustrated myself. It should be something very simple and yet it's refusing to work. I'm assuming I am doing something wrong at a basic level but I've reached the point where my brain refuses to see it.
Here is the basic script I started with:
function doGet(e) {
var app = UiApp.createApplication();
var mainPanel = app.createVerticalPanel().setId('mainPanel');
mainPanel.add(app.createLabel('test'));
return app;
}
I save it, publish it and go to the URL and that's when I get the above error message. I know it's something simple but I've reached the point of frustration and simply can't see it.
Update: to reflect comments
Another possibility for WebApps not updating is not publishing a new version and only checking the exec URL. For instant changes to the code, always check the dev URL. The exec will only change after saving a version in Manage Versions and re-publishing the app.
First Answer:
I think your question title says it all.
UIApp is not defined, but Class is UiApp. JS is case sensitive. I copied and pasted the code exactly as it is in your question and received no errors. I did have to add one line to make the label show up.
function doGet(e) {
var app = UiApp.createApplication();
var mainPanel = app.createVerticalPanel().setId('mainPanel');
mainPanel.add(app.createLabel('test'));
app.add(mainPanel); // <-- I added this line to see the label
return app;
}

Problems using the Apps Script GUI builder

So I'm currently working on the gui of an item checkout system that runs within a spreadsheet. It does everything it's supposed to and isn't returning anything null, usually I'd be really happy with how it's turning out.
However, I keep getting "error encountered, an unexpected error occured" whenever I press the submit button, after that the rest of the code runs as expected. Every once and a while I'll get no error, but the vast majority of the time it throws the error.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [{name: "Equipment Checkout", functionName: "testing"}];
ss.addMenu("Equipment Checkout", menuEntries);
}
function testing(){
var app = UiApp.createApplication();
app.add(app.loadComponent("ImprovedCheckout"));
var doc = SpreadsheetApp.getActiveSpreadsheet();
doc.show(app);
}
function submitted(e){
Browser.msgBox(e.parameter.requestor);
}
This is the simplest version of my code.
I'm using the gui builder to create the gui and I'm also using it to make the event handler. I've been banging my head against the wall for the past hour because it seems like the error is happening before the first line of submitted(e) but it doesn't occur until I actually click the submit button. It doesn't happen every time but it does happen the majority of the time.
I imagine I'm handling events from the builder wrong but there is oh so little information on that feature yet.
I've seen this error happen when people set two handlers for the same button. Normally one via the GUI editor and another on the code. One works and the other fails. Which gives this crazy impression that it throws an error and yet works.
But since you said this is the exact code you're using. Are you setting multiple handlers on the GUI builder? I don't know even if that's possible, I never use the GUI builder.
FIGURED IT OUT!
Instead of using a submit button, I changed it to just a regular old button. It looks like the submit button was trying to run something else at the same time.
It looks like submit buttons have some additional rules and requirements but for the time being, I'm just using a normal button.
I have had no issues running the code you have supplied. Two things to mention that are key:
Make sure that you're adding a callback element to the ServerHandler with the HTML name of "requestor" as you are using in code.
When you add the callback element, use the ID in the GUI editor. Name != ID
Both Name and ID need to be set in this example.
I have got this same error message when using getElementbyId('id") and having a wrong value as ID. The script itself don't really stop and everything might seem normal apart from the action this specific call is supposed to do (but this is not always 'obvious')