I want to do some text/paragraphs replacement in Google Docs that are automatically created by an add-on (autoCrat). I tried this successfully on a bound script but now that I want to try it on a standalone script, I get this error:
TypeError: Function getBody not found in the DOCUMENT-NAME object.
I don't understand.
Do I need to call a bound script from the standalone script or something like that?
(I hope not.)
The GAS documentation is not helping at all with this, at least with my understanding of what a standalone script is. Maybe it's a trivial error, but all the examples I found here are for bound scripts, which are not what I'm doing (I've already done a bound script and it's working fine).
This very simple code won't work for a standalone script and I don't understand why :
function Myfunction() {
var file = DriveApp.getFileById('doc-id');
var body = file.getBody();
Logger.log(body);
}
You are getting that error because the class returned by getfilebyID is of type File, not Document.
Try something like this:
let LogFile = DriveApp.getFileById('doc-id');
let LogDoc = DocumentApp.openById(LogFile.getId());
LogDoc.getBody()
Related
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!
Suddenly my script get the error:
Cannot find method setMimeType((class)) (line xxx, file "Code")
It worked well for years, until this afternoon. I didn't modified it at all.
What I've done after:
copied this code from google documentation:
function doGet() {
var feed = UrlFetchApp.fetch('http://xkcd.com/rss.xml').getContentText();
feed = feed.replace(
/(<img.*?alt="(.*?)".*?>)/g,
'$1' + new Array(10).join('<br />') + '$2');
return ContentService.createTextOutput(feed)
.setMimeType(ContentService.MimeType.RSS);
}
pasted it into a new script
given it the proper authorizations
run it
It was ok.
Then:
renamed the doGet() function into doGet1() in my broken script
pasted the example doGet() function code
run my script (doGet function)
I obtained the same error:
Cannot find method setMimeType((class)) (line xxx, file "Code")
What could have happened?
i just had the same error. my script stopped working.
it looks like the "ContentService.MimeType.RSS" does no longer exist.
"RSS" is no longer an autocomplete option if you type that.
i changed it to the "ContentService.MimeType.TEXT".
it is the closest option.
i also had to make a new deployment after saving the new code.
now my script is working again.
Trying to debug my script, a message informed me that my project uses an old Apps Script runtime, and that in order to execute debug I have to upgrade to Javascript V8 engine. After doing that, everything went back to normal.
I attach a screenshot (from a different script, in Italian language).
Since I tend to ramble, first a short version and if you need more information read the long one.
TL;DR
Why is this:
function doGet(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var jobsCreated = sheet.getRange(12,2).getValue();
Browser.msgBox(jobsCreated);
var params = JSON.stringify({number:jobsCreated});
return ContentService.createTextOutput(params);
}
returning this when I published as website and then open:
{"number":""}
when it should look more like this {"number":2451}
Full Version:
First of all, I learned to program back in uni for my Computer science degree (10 years ago) but since then I haven't done much programming so I am basically a newbie.
Now to the question. I have a very simple script that a created with the script editor from Google Sheets
function doGet(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var jobsCreated = sheet.getRange(12,2).getValue();
Browser.msgBox(jobsCreated);
var params = JSON.stringify({number:jobsCreated});
return ContentService.createTextOutput(params);
}
First I get the sheet I am working on
Then I select a cell from that sheet
now if I use a msgBox to make sure that I have the right number and run the script, it works and it shows the message.
next, I format the variable as JSON and finally I just create a text output.
Now I deploy as Web app
Execute as ME
Anyone, even anonymous
And when I access the website I can only see this:
{"number":""}
If I change the code and give jobsCreated and static value it works fine
var jobsCreated = 100;
{"number":100}
So my conclusion is that the problem is with accessing the value of the cell when running the script from the published link compare to running it directly from the editor, but I have no idea how to fix this.
A little bit more information, i am trying to use this for a counter called Smiirl, i got most of the information from here
https://medium.com/#m_nebra/bootstrapping-your-company-counter-22f5d4bc7dd4
try this:
function doGet(e) {
return ContentService.createTextOutput(Utilities.formatString('number: %s',SpreadsheetApp.getActiveSheet().getRange(12,2).getValue());
}
Ok as I replied to #Aerials, thank you again for your help btw. Seeing other codes that should work not working with my script, I decided to create a new sheet and script as a test and with the exact same code it works.
But now checking on it a little bit more, something that I didn't think it was a problem since it was getting the number without any problems. The cell it's being populated by a GoogleAnalytics add-on. Now when setting up the add-on again to get the information the script from the website returns an empty value again. SO it seems the issue is with the script getting the information from the sheet (only the published version) when its being populated by the add on
Your issue is in the use of JSON.stringify
In JSON, functions are not allowed as object values.
The JSON.stringify() function will omit or change to null any functions from a JavaScript object.
That said, you can do the following:
function doGet(e){
// Get the value of the range
var sheet = SpreadsheetApp.getActiveSheet();
var jobsCreated = sheet.getRange(12,2).getValue();
// JSON Stringify it
var params = JSON.stringify({"number" : number=jobsCreated});
// Return JSON string
return ContentService.createTextOutput(params);
}
Returns:
{"number":123} if jobsCreated is the number 123, or
{"number":"Mangos"} if jobsCreated is the string "Mangos".
See it the script deployed here, and the sheet to play with.
Note:
You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.
I've tried as many combinations as I could come up with.
My goal is to have a Google Apps Script running StandAlone or from a Library and be able to set Named Ranges in a spreadsheet.
As best I can figure it, the setNamedRange() method is only available from within the Spreadsheet container and only when you use SpreadsheetApp.getActiveSpreadsheet().
I tried using openById() to no avail. The method is just not available.
Thought I was clever and tried openById then setActiveSpreadsheet. I wasn't clever enough.
Update, I opened issue 1816 "Object become global, auto complete persists even when deleted" with google-apps-script-issues http://code.google.com/p/google-apps-script-issues/issues/detail?id=1816
Quite interesting behavior. Misled me into asking the wrong question
Looks to be a bug in the GAS editor.
The following function demonstrates how to set a named range in a standalone script.
function testNamedRange() {
var ss = SpreadsheetApp.openById('here is the spreadsheet id');
var range = ss.getRange('Sheet1!A1:B2');
ss.setNamedRange('TestRange', range);
var rangeCheck = ss.getRangeByName('TestRange');
var rangeCheckName = rangeCheck.getA1Notation();
}
The rangeCheckName variable contains the A1:B2 string.
I am generating a document using Google App Script (specifically a document, not a spreadsheet) and I need to be able to add it to a folder I have called "Test Documents".
I have tried
doc.addToFolder("Test Documents");
However, in debug mode I get the error that the method addToFolder is not found. I'm trying to use this functionality: https://developers.google.com/apps-script/class_file#addToFolder
Could someone give me an example of how I might do this?
The method addToFolder is part of DocsList service, here is an example :
var Doc = DocsList.getFileById('1INkRIviwdjMC-PVT9io5LpiiLW8VwwIfgbq2E4xvKEo');
var gas = DocsList.getFolderById('0B3qSFd3iikE3NWY0dndsMTFZMDQ')
Doc.addToFolder(gas)