Tag Archives: Apps Script

Deprecating ScriptDB and Domain Service in Apps Script

In the last few months, we've added a number of new features to Google Apps Script, including add-ons for Sheets and Docs and 7 new advanced services.

We're eager to maintain that momentum — focusing on new features that help you do more with Google Apps. As a result, we're deprecating two Apps Script services for which good replacements exist elsewhere: ScriptDB (a NoSQL database that has been marked as experimental since it was introduced) and the Domain service (which encapsulates the GroupsManager, NicknameManager, and UserManager global objects).

Both ScriptDB and the Domain service will be turned off on November 20, 2014.

Before then, you'll need to port any ScriptDB projects to another data store, like Google Cloud SQL or a third-party NoSQL database. We've created a migration guide that explains how to export your data from ScriptDB and suggests a few alternate data stores. We have also improved the documentation for connecting to external databases through JDBC to make it a little easier for you to set up Cloud SQL with Apps Script.

The Domain service, which only Google Apps domain administrators can use, is replaced by the recently added Admin SDK Directory and Admin SDK Reports advanced services. Those advanced services also provide many new features that the Domain service does not — like managing users' devices, OAuth tokens, and application-specific passwords — so we expect that you'll prefer using them in the future.


Saurabh Gupta   profile | twitter | blog

As the product manager for Google Apps Script, Saurabh is responsible for Apps Script’s overall vision and direction.

Build add-ons for Google Docs and Sheets

We've just announced Google Docs and Sheets add-ons — new tools created by developers like you that give Google users even more features in their documents and spreadsheets. Joining the launch are more than 60 add-ons that partners have built using Apps Script. Now, we're opening up the platform in a developer-preview phase. If you have a cool idea for Docs and Sheets users, we'd love to publish your code in the add-on store and get it in front of millions of users.


To browse through add-ons for Docs and Sheets, select Get add-ons in the Add-ons menu of any document or spreadsheet. (Add-ons for spreadsheets are only available in the new Google Sheets).


Under the hood

Docs and Sheets add-ons are powered by Google Apps Script, a server-side JavaScript platform that requires zero setup. Even though add-ons are in developer preview right now, the tools and APIs are available to everyone. The only restriction is on final publication to the store.

Once you have a great working prototype in Docs or Sheets, please apply to publish. Scripts that are distributed as add-ons gain a host of benefits:

  • Better discovery: Apps Script has long been popular among programmers and other power users, but difficult for non-technical users to find and install. Add-ons let you distribute your code through a polished storefront—as well as direct links and even Google search results.
  • Sharing: When two people collaborate on a document and one of them uses an add-on, it appears in the Add-ons menu for both to see. Similarly, once you get an add-on from the store, it appears in the menu in every document you create or open, although your collaborators will only see it in documents where you use it. For more info on this sharing model, see the guide to the add-on authorization lifecycle.
  • Automatic updates: When you republish an add-on, the update pushes out automatically to all your users. There's no more hounding people to switch to the latest version.
  • Share functionality without sharing code: Unlike regular Apps Script projects, add-ons don't expose your source code for all to see. That's reassuring both to less-technical users and to the keepers of your codebase's secrets.
  • Enterprise features: If your company has its own Google Apps domain, you can publish add-ons restricted just to your employees. This private distribution channel is a great way for organizations that run on Google Apps to solve their own unique problems.

Beautiful, professional appearance

Thanks to hard work from our developer partners, the add-ons in the store look and feel just like native features of Google Docs and Sheets. We're providing a couple of new resources to help all developers achieve the same visual quality: a CSS package that applies standard Google styling to typography, buttons, and other form elements, and a UI style guide that provides great guidance on designing a Googley user experience.


A replacement for the script gallery

Add-ons are available in the new version of Google Sheets as a replacement for the older version's script gallery. If you have a popular script in the old gallery, now's a great time to upgrade it to newer technology.

We can't wait to see the new uses you'll dream up for add-ons, and we're looking forward to your feedback on Google+ and questions on Stack Overflow. Better yet, if you're free at noon Eastern time this Friday, join us live on YouTube for a special add-on-centric episode of Apps Unscripted.


Dan Lazin   profile | twitter

Dan is a technical writer on the Developer Relations team for Google Apps Script. Before joining Google, he worked as video-game designer and newspaper reporter. He has bicycled through 17 countries.

More Apps Script APIs and Features

Developers like you have built amazing scripts with Apps Script, and we want to make Apps Script even more useful. We've been working hard to add a variety of new APIs and features in Google Apps Script. Today, we're ready to share a few of them with you.


New in Document service: named ranges, bookmarks, setting cursor or selection, and undo

Named ranges are a popular feature of the Spreadsheet service; and now, you’ll be able to do something similar in the Document service. With named ranges, your scripts can tag a section of a Google Doc for later reference. For example, a bibliography script could set a named range on every citation in a document, then easily update the citations in the future.


You can use a similar API to manage bookmarks, too. Unlike named ranges, bookmarks are visible to the user and allow you to link to a particular place in a document.

Also for Google Docs, we've added the server-side methods setCursor(position) and setSelection(range) to change the user's cursor position or active selection, plus a client-side method, google.script.host.editor.focus(), which switches the browser focus from a sidebar or dialog back to the document.

Oh, and hey: the Undo command in Google Docs can now revert changes made by a script.


New in HTML service: NATIVE mode by default

If you've used HTML service much, you'll know that the Caja security sandbox has two modes. NATIVE mode imposes fewer restrictions than EMULATED mode and generally runs faster. As of today, NATIVE is now the default if you have not specified which mode your script should use. In a few edge cases, this may affect how existing web apps operate; if so, simply append .setSandboxMode(HtmlService.SandboxMode.EMULATED) to your HtmlOutput object to restore the old behavior.


Revised Properties service

In preparation for future improvements to Apps Script, we've revamped script properties and user properties, combining them into a unified Properties service and adding the notion of document properties, which are (surprise!) specific to a particular document, but shared among all collaborators. The biggest change is that user properties are no longer shared between scripts, but our guide to the Properties service provides all the details. As part of the change, the old ScriptProperties and UserProperties services have been deprecated, although they will continue to function in existing scripts until a sunset date is announced.


Deprecation of Finance service

We’re excited to bring you these new tools. With these new additions, we have also deprecated Finance service. It will remain available for the next six months but will be turned off on September 26, 2014.


Saurabh Gupta   profile | twitter | blog

As the product manager for Google Apps Script, Saurabh is responsible for Apps Script’s overall vision and direction.

Building on YouTube APIs in the cloud with Google Apps Script

There’s nothing better in this world than a great pairing, like coffee and donuts or bees and honey. Today there’s a new one to add to the list: Google Apps Script now has built in support for the YouTube Data v3 and YouTube Analytics APIs. If you haven’t yet heard of Google Apps Script, you’re missing out on an easy-to-use tool for integrating and automating common tasks across many of Google’s services. With less than half a screen’s worth of code in Google Apps Script’s cloud-based editor, you can:

  • Dynamically update a spreadsheet containing watch-time statistics for all of your channel's videos, with all the flexibility and power of Google Sheets to sort and slice that data
  • Create a live dashboard or scheduled email report about your channel's performance
  • Handle channel management tasks such as scheduling automatic bulletins or changing the visibility of a large number of videos from private to public
  • Automate playlist rotation without having to maintain a server or keep a computer for the sole purpose of running a script
Google Apps Script's cloud-based environment and autocomplete functionality make it easy to just open an editor, enable the YouTube APIs, and start writing code:



For functions that require OAuth 2.0 authorization, there’s no authorization code to write and no token management to deal with. Once your script is ready, just click “Run” and Google Apps Script will present you with an authorization dialog. Once you select the channel you want to authorize, the script will have all of the permissions it needs to operate on your behalf, running in the background at scheduled intervals if you so desire.

To get started, browse to Google Drive. Click “Create” and then choose “Script”. This will open a new browser tab to the Google Apps Script editor. Name your project and click on “Resources” and select “Advanced Google Services”:


Toggle the YouTube Data API and/or YouTube Analytics API on:


Note the message that these services must be enabled in the API console. Click the link to be taken to the Google Developer Console. The link in the message will take you to a specific API project created for this specific Apps Script. Scroll down and toggle on the YouTube APIs the script will use:


Switch back to the tab containing Google Apps Script and click “OK”. You’re ready to start writing code. Type “YouTube” and hit the period key (“.”). If the APIs have been turned on correctly, you will be able to start writing code and calling functions available in the Data API or Analytics API. For instance, a short script that searches for videos about “dogs” and prints the video IDs to the Google Apps Script log would look like this:


function searchByKeyword() {
var results = YouTube.Search.list("id,snippet",
{q : "google apps script", maxResults: 25});

for(var i in results.items) {
var item = results.items[i];
Logger.log("[%s] Title: %s", item.id.videoId, item.snippet.title);
}
}

For more information about this update to Google Apps Script, check out the post on their official blog. To learn more about how to integrate scheduled jobs, write to spreadsheets or any of the many things Google Apps Script can do, check out the tutorials at their home at developers.google.com/apps-script. If you’re the type that prefers to learn on the go, get started with your own copy of our sample code in your Google Drive. You will still need to enable the APIs, so don’t forget to go to “Resources > Advanced Google services” for the link to the Developer Console project to turn on the APIs.


If you have any questions, feel free to find us on StackOverflow under the youtube-api and google-apps-script tags. Happy coding!


- Ikai Lan
YouTube Developer Relations

More Google services available in Apps Script

One of things that makes Apps Script great is its ability to act as a hub for various types of Google data. In addition to our built-in services for popular products such as Gmail, Drive, Docs, and Calendar, we also provide a line of advanced Google services that let you use existing Google APIs such as Analytics and Tasks. Today, we're expanding that family of advanced services to include the following:

From Google Apps administrators and data-heads to Glass Explorers and YouTube content creators, this collection of new services has something for everyone. Getting started with advanced services is easy, since we take cake of the authorization for you and even provide autocomplete in the script editor.

While our built-in services are hand-crafted for ease-of-use, our advanced services are automatically generated from existing public Google APIs. They provide access to the full power of the underlying API but can be slightly more difficult to use. Let's look at some sample code that searches for YouTube videos with the keyword "dogs".

function searchByKeyword() {
var part = 'id,snippet';
var optionalArgs = {
q: 'dogs',
maxResults: 25
};

var results = YouTube.Search.list(part, optionalArgs);

for (var i = 0; i < results.items.length; i++) {
var item = results.items[i];
Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
}
}

This function uses the YouTube.Search.list() method, which has a required parameter part and optional parameters q and maxResults, among others. Required parameters are passed individually as method arguments, while optional parameters are passed as one key-value map. The full list of parameters this method accepts can be found in the YouTube API's reference documentation.

We're also changing our advanced services to behave more like vanilla JavaScript, so that it's easier to reference the APIs' existing documentation. You can now pass native JavaScript objects into these services' methods, and access the results using regular dot-notation. Below is some sample code that adds a new user to a Google Apps domain.

function addUser() {
var user = {
primaryEmail: '[email protected]',
name: {
givenName: 'Elizabeth',
familyName: 'Smith'
},
// Generate a random password string.
password: Math.random().toString(36)
};
user = AdminDirectory.Users.insert(user);
Logger.log('User %s created with ID %s.', user.primaryEmail, user.id);
}

Notice that the user resource is constructed as a plain object literal, and the ID of the created user is accessed via dot-notation. The legacy getter/setter notation will continue to work but will no longer appear in autocomplete.

Finally, it's worth reminding that advanced Google services must be enabled in each script that uses them. This involves toggling them on once in the script editor under Resources > Advanced Google services and again in the associated Google Developers Console project.


Eric Koleda profile

Eric is a Developer Programs Engineer based in NYC on the Google Apps Script team. He's previously worked with the AdWords API and enterprise content management software.

Code updates required for Apps Script advanced services

The APIs for three of Apps Script's advanced servicesAnalytics, BigQuery, and Prediction — will undergo breaking changes on Monday, November 18. If you don't update your code to the new syntax before then, you'll receive error messages such as Required parameter is missing.

Advanced services allow you to easily connect to certain public Google APIs from Apps Script. We're working to expand and improve our advanced services, and as a side effect some methods and parameters that were incorrectly listed as optional are now required.

On November 18, these services will switch to use the new method signatures shown in the tables below. To learn how new arguments should be structured, refer to the documentation for the underlying API. For example, the documentation for the BigQuery service's Jobs.query()method shows the valid properties for the resource object in the "Request body" section of the page.


OldNew
Analytics.Management.Uploads

.deleteUploadData(
accountId,
webPropertyId,
customDataSourceId,
optionalArgs)

.deleteUploadData(
resource,
accountId,
webPropertyId,
customDataSourceId)
BigQuery.Datasets

.insert(
resource,
optionalArgs)

.insert(
resource,
projectId)

.update(
resource,
optionalArgs)

.update(
resource,
projectId,
datasetId)
BigQuery.Jobs

.insert(
resource,
mediaData,
optionalArgs)

.insert(
resource,
projectId,
mediaData)

.query(
projectId,
query)

.query(
resource,
projectId)
BigQuery.Tabledata

.insertAll(
projectId,
datasetId,
tableId,
optionalArgs)

.insertAll(
resource,
projectId,
datasetId,
tableId)
BigQuery.Tables

.insert(
resource,
optionalArgs)

.insert(
resource,
projectId,
datasetId)

.update(
resource,
optionalArgs)

.update(
resource,
projectId,
datasetId,
tableId)
Prediction.Hostedmodels

.predict(
project,
hostedModelName,
optionalArgs)

.predict(
resource,
project,
hostedModelName)
Prediction.Trainedmodels

.insert(
project,
optionalArgs)

.insert(
resource,
project)

.predict(
project,
id,
optionalArgs)

.predict(
resource,
project,
id)

.update(
project,
id,
optionalArgs)

.update(
resource,
project,
id)

If you want to prepare your code ahead of time, you can add a try/catch around your existing code that retries with the new method signature if the old one fails. For example, the following sample applies this approach to the BigQuery service's Jobs.query() method:


var result;
try {
result = BigQuery.Jobs.query(projectId, query, {
timeoutMs: 10000
});
} catch (e) {
// Refer to the BigQuery documentation for the structure of the
// resource object.
var resource = {
query: query,
timeoutMs: 1000
};
result = BigQuery.Jobs.query(resource, projectId);
}

We apologize for inconvenience and look forward to sharing exciting news about advanced services in the coming weeks.


Eric Koleda profile

Eric is a Developer Programs Engineer based in NYC on the Google Apps Script team. He's previously worked with the AdWords API and enterprise content management software.

Total Eclipse of the Apps Script

Apps Script started out as a simple tool to let developers add new features to Google Apps, but it’s grown into a programming platform that thousands of professional coders use every day. We hear a couple common requests from developers when they’re building complex projects with Apps Script: they want a full-featured IDE, and they want to sync to external version-control systems like GitHub.

Today, we’re introducing support for Apps Script in the Google Plugin for Eclipse. You can now sync with your existing Apps Script files on Google Drive, edit them in Eclipse — offline, if necessary, and with all the benefits of autocomplete — then write your code back to Drive so you can run it in the cloud. Because the plugin stores a copy of each script in a local workspace, you can manage Apps Script projects with your favorite version-control system.


Getting started is easy:

  1. Install Eclipse, if you don’t already use it. If you already have Eclipse, make sure it’s at least version 3.7 (Indigo) for either Java or Java EE.
  2. In Eclipse, select Help > Eclipse Marketplace, then install the Google Plugin for Eclipse (or see our Getting Started guide for alternate installation instructions).
  3. Click Sign in to Google in the bottom-right corner of Eclipse, then enter your username and password.
  4. Select File > Import to transfer your projects into Eclipse. Whenever you’re online, the plugin will automatically sync your local edits with Google Drive.

For step-by-step instructions on installation and use, see the documentation on using Apps Script with the Google Plugin for Eclipse.

Just in case you were wondering, the plugin uses the public Google Drive SDK to sync Apps Script files between your local file system and Google’s servers. We’ve previously covered the techniques it uses in our documentation on importing and exporting projects and the recent episode of Apps Script Crash Course on Google Developers Live below.




Norman Cohen   profile

Norman Cohen is a software engineer based in Google’s New York office. He works primarily on the Google Plugin for Eclipse, focusing on improving developer experience in the cloud.

YouTube, Google Forms, and Apps Script: BFFs

Last month, we announced several new ways to customize Google Forms. As of this week, three of those options are also available in forms created from Apps Script — embedding YouTube videos, displaying a progress bar, and showing a custom message if a form isn’t accepting responses.


Adding a YouTube video is as simple as any other Google Forms operation in Apps Script — from the Form object, just call addVideoItem(), then setVideoUrl(youtubeUrl). Naturally, you can also control the video’s size, alignment, and so forth.

To show a progress bar, call setProgressBar(enabled). Don’t even need a second sentence to explain that one. The custom message for a form that isn’t accepting responses is similarly easy: setCustomClosedFormMessage(message), and you’re done.

Want to give it a try yourself? Copy and paste the sample code below into the script editor at script.google.com, then hit Run. When the script finishes, click View > Logs to grab the URL for your new form, or look for it in Google Drive.

function showNewFormsFeatures() {
var form = FormApp.create('New Features in Google Forms');
var url = form.getPublishedUrl();

form.addVideoItem()
.setVideoUrl('http://www.youtube.com/watch?v=38H7WpsTD0M');

form.addMultipleChoiceItem()
.setTitle('Look, a YouTube video! Is that cool, or what?')
.setChoiceValues(['Cool', 'What']);

form.addPageBreakItem();

form.addCheckboxItem()
.setTitle('Progress bars are silly on one-page forms.')
.setChoiceValues(['Ah, that explains why the form has two pages.']);

form.setProgressBar(true);

form.setCustomClosedFormMessage('Too late — this form is closed. Sorry!');
// form.setAcceptingResponses(false); // Uncomment to see custom message.

Logger.log('Open this URL to see the form: %s', url);
}

Dan Lazin   profile | twitter

Dan is a technical writer on the Developer Relations team for Google Apps Script. Before joining Google, he worked as video-game designer and newspaper reporter. He has bicycled through 17 countries.

Answering another top request: data validation in Apps Script

Google Apps Script is, first and foremost, a tool for making Google Apps more powerful — and today’s addition of programmatic control over data-validation rules in Google Sheets is a perfect example. For a quick demo, make a copy of this spreadsheet, then follow the instructions provided.


For the last few months, scriptable access to the data validation feature in Sheets has been the most requested feature on the Apps Script issue tracker. A common use for data-validation rules is to require that a cell’s value match one of the values in a different range. The following example shows how to achieve that goal with Apps Script. First, we use the newDataValidation() method to construct a DataValidationBuilder, then set the appropriate options and apply the final DataValidation with setDataValidation().


// Set the data-validation rule for cell A1 to require a value from B1:B10.
var cell = SpreadsheetApp.getActive().getRange('A1');
var range = SpreadsheetApp.getActive().getRange('B1:B10');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(range)
.build();
cell.setDataValidation(rule);

It’s also possible to modify existing data-validation rules. The next example changes rules that require a date in 2013 to require a date in 2014 instead. You’ll see that the script calls getDataValidations() to retrieve the existing rules, then uses getCriteriaType(), getCriteriaValues(), and the DataValidationCriteria enum to examine the rules before applying the new date restriction via the advanced withCriteria() method.


// Change existing data-validation rules that require a date in 2013
// to require a date in 2014.
var oldDates = [new Date('1/1/2013'), new Date('12/31/2013')];
var newDates = [new Date('1/1/2014'), new Date('12/31/2014')];
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
var rules = range.getDataValidations();

for (var i = 0; i < rules.length; i++) {
for (var j = 0; j < rules[i].length; j++) {
var rule = rules[i][j];

if (rule != null) {
var criteria = rule.getCriteriaType();
var args = rule.getCriteriaValues();

if (criteria == SpreadsheetApp.DataValidationCriteria.DATE_BETWEEN
&& args[0].getTime() == oldDates[0].getTime()
&& args[1].getTime() == oldDates[1].getTime()) {
rules[i][j] = rule.copy().withCriteria(criteria, newDates).build();
}
}
}
}
range.setDataValidations(rules);

With this new feature in Apps Script, you should find it much easier to manage complex data-validation scenarios. Please keep the feature requests coming!


Asim Fazal   profile

Asim is a software engineer on the Google Sheets team in New York — and an enthusiastic occasional contributor to the Apps Script team.

An update to authorization in Apps Script

For developers, part of the simplicity of Apps Script has always been that authorization requires zero setup — but we heard from users that the process required too many clicks. At Google I/O this year, we launched an opt-in version of an easier authorization flow; today, that new flow becomes the default for all new scripts.


The old way — and the new.

Besides being prettier and easier, the new flow offers benefits behind the scenes: it allows more scripts to be simultaneously authorized on the same account, which means you shouldn’t need to reauthorize a script unless the code changes substantially.

For developers who use the advanced Google services, the new flow also gets rid of some manual steps that were previously required. Every new script now automatically creates a project in the Google APIs Console — no more messing with secret keys!

If you want the same experience for your existing scripts, you can upgrade them manually in just a few seconds.


Steve Lieberman   profile

Steve is an engineer on the Apps Script team in NYC. Before joining Google, he developed financial-trading systems and researched automatically-parallelizing compilers.