How do I use Google Apps Script on a single question in Google Forms? - google-apps-script

I've started doing a Google Form, however I'd like to use G.A.S to do some custom questions, lists, etc. I have found the code to try and I've entered it into the Script Editor, but I don't see how to set the code to specific sections or questions. How do I specify where the code should run?

This will add a short answer question to a form.
function addAQuestionToAForm() {
const form=FormApp.getActiveForm();
form.addTextItem().setTitle('Phone Number');
}
Here's the form:

Related

Google Apps Script Gmail getPlainBody Line Breaks

With the Google Apps Script Gmail library, when I use the function GmailMessage.getPlainBody(), the API seems to take what used to be one paragraph and break it up into multiple, potentially by using a character limit. For instance, a paragraph of my email reads:
From the link you sent me, I gleaned that Gmail refers to their secure email as confidential.
But when I call this function on the email, it becomes:
From the link you sent me, I gleaned that Gmail refers to their
secure email as confidential.
And, when I split the email text on a new line delimitor and do a bit of cleanup to create an array with my output, I end up with:
['From the link you sent me, I gleaned that Gmail refers to their', 'secure email as confidential.']
I viewed this Reddit post, which seemed to deal with the similar problem. But, I tried the resolution suggested by the person who posed the question:
body = message.getPlainBody().replace(/\r\n\r\n/gm,'aaaLINEBREAKERaaa').replace(/\r\n/gm,' ').replace(/aaaLINEBREAKERaaa/gm, '\r\r').replace(/ /gm,' ')
And it didn't quite give me what I need. Has anyone else encountered this problem, and if so, do you have a suggested workaround? Thanks!
I had the same issue. In that case, I used a workaround.
When I checked the email, I noticed that the HTML body is included in the message body and the HTML body has the original paragraph, and I used this situation. So, in this workaround, the original text is retrieved from the HTML body and the HTML is converted to a text. By this, the original paragraph is obtained. The sample script is as follows.
Sample script:
This script uses Drive API for converting HTML to text. So pelase enable Drive API at Advanced Google services.
var message = // Here, please use your "message".
var html = message.getBody();
var id = Drive.Files.insert({title: "temp", mimeType: MimeType.GOOGLE_DOCS}, Utilities.newBlob(html, MimeType.HTML)).id;
var text = DocumentApp.openById(id).getBody().getText(); // or DocumentApp.openById(id).getBody().getText().trim();
DriveApp.getFileById(id).setTrashed(true);
console.log(text)
References:
getBody()
Files: insert

Is it possible to add a comment attributed to specific text within Google Docs using Apps Script?

Google docs comment:
My goal is to add a text-specific comment using Google Apps Script as seen in the picture above. Right now I have this working code, but it only adds a general comment for the whole document.
function myFunction() {
var fileId = '{FILE_ID}';
var resource = {'content': 'comment body text'};
Drive.Comments.insert(resource, name);
}
Not possible. In this video -- Google Drive SDK: Announcing the Comments API (5:30 - 5:39) -- it is mentioned that:
..We do have a proprietary anchoring scheme, which does make it difficult for, or actually rather impossible for you to create comments that are anchored to text in our document formats...
"in our document formats" refers to Google Docs and Sheets.
This is also mentioned in this answer. For more details regarding Comments, you can check the Manage Comments and Discussions documentation.

Retrieving HTML code used in google docs using google app scripts

Is it possible to use Google app scripts to get the html code in Google docs i.e if text in the document was say bold,i could get the html code for that.
What i have so far :
function getHtml(id) {
var doc1=DocsListExtended.getFileById("1ta7zJ6SDFgzgp-UprjehxR8Tx3-4-wtJwTYqWbol1SU").getAsHTML();
var body=HtmlService.createHtmlOutput(doc1);
var cont=body.getContent();
return cont;
Logger.log(cont);
}
I don't know a simple way for that. You can navigate the elements of the document using DocumentApp API, and converting it block by block to HTML.
I already tried
DocumentApp.getActiveDocument().getAs(MimeType.HTML).getDataAsString()
but the error says doc can't be converted to html mimetype.

How to Convert a simple Google text-only Document to HTML via Google Apps Script? [duplicate]

This question already has answers here:
Get Google Document as HTML
(8 answers)
Closed 1 year ago.
I need to take the contents of a Google Doc and turn it into the HTML code equivalent (for sending as an HTML email), via Google Apps Script.
I can read the file and get the text by cycling thru the elements in the body, but how would one get the formatting (bold, italic) into HTML? Via isBold(offset) and isItalic(offset) and cycling thru each character?
Thanks for any help. ~
This is perfectly doable using a document to compose your message, converting it to html format and using that as an html body in the message.
the code goes like this :
function sendAsHtmlBody(){
var id = DocumentApp.getActiveDocument().getId();
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
googleOAuth_('docs',url)).getContentText();
MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'testHTML Body','html content',{'htmlBody':doc});
}
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
This code will ask for authorization in 2 steps, one for "normal" services (mail, documentApp, ..) and a second for the Oauth function, this latter must be triggered by calling the function from the script editor (if you make a menu and let a new user call that menu it won't work..., you have to use the script editor, see issue 677 here).
And here is a shared document( read only, make a copy to use) to test the code with different fonts, an image and some text.(almost every feature available in Google docs are translated in html... only a few alignment are missing sometimes. I use that very often without noticeable issue)
Is the default sharing option not enough? I know you can select the option to display in email. Just a thought.
You may want to look for another solution, as I am as well. When I go to use this I hget a message stating:
OAuthConfig API is deprecated
Method UrlFetchApp.addOAuthService is deprecated

How to pass parameters to Google Apps Script Gadget embedded in a Sites Page?

I have a Google Apps Script gadget that is embedded in a Google Sites page. I would like to pass the gadget a page parameter, such that when the page is opened with URL like:
https://sites.google.com/a/mydomain/mysite/mypage?myparameter=1
I can access the value of the page parameter in the Apps Script gadget code like so:
function doGet(e) {
var app = UiApp.createApplication();
app.add(app.loadComponent("MyComponent"));
var myparam = e.parameter.myparameter;
return app;
}
Currently, the value of e.parameter.myparameter is coming back as null. Is there a way to setup my Apps Script to support this? Any approaches are welcome.
Maybe the link bellow will help you - I have not tried it myself yet...but I will try it out in the next days.
http://code.google.com/p/google-apps-script-issues/issues/detail?id=535
I posted this on the code.google.com page linked in the accepted answer, but the way to have parameters passed through to Apps Script is by adding "https://sites.google.com/feeds" to the Apps Script scope. (See this site for information about how to add explicit scopes.) Once this scope is added, the following works:
in Code.gs:
function doGet(e) {
var htmlTemplate = HtmlService.createTemplateFromFile("page");
htmlTemplate.urlParams = e.parameters;
return htmlTemplate.evaluate();
}
in page.html:
...
<head>
...
<script>urlParams = <?!= JSON.stringify(urlParams) ?>;</script>
</head>
...
urlParams is now available as a variable in your JS code in the following form:
urlParams = { key1: [value1, value2, ...], key2: [value1, value2] }
This example describes a parameter as "&name=value" however I have not been able to get it working in either a Google Apps Site, or in a Personal Google Site. (which seem to handle authentication in different ways)
The example seems to work fine when I hard-code the value so maybe I am just not parsing it right or something, I will try to follow up here when I understand this better but I also have not yet found adequate explanations of these features.
One Hypothesis is that Google changed something, I note the menu structure does not seem to match what I assume it use to be since I see many references to a [share] button/menu.