Google
 Google Gadgets API Developer Guide: Getting Started
 

For Users
  Content Directory
  User Forum

For Developers
  Overview
  Developer Guide
    Getting Started
    Advanced Tasks
      Internationalization
      Syndicated Gadgets
  API Reference
  Developer FAQ
  Google Gadgets for
     Your Page
  Submit a Gadget
  Terms and Conditions
  Developer Forum



Google Desktop API
Write handy plug-ins for Google Desktop Search.

Google Maps API
Embed Google Maps in your webpages and add your own overlays.


The Google Gadgets API provides a way to put third-party content onto the Google homepage, other Google properties, and with the introduction of open syndication, any web page. A gadget is a mini-application, such as a photo album or an interactive game. The API is designed to be simple enough so that anyone can turn his or her web page or application into a gadget.

For advanced programming tasks, see Part 2 of the Google Gadgets API Developer Guide.

Table of Contents

Introduction
Audience
"Hello, World"
Writing Your Own Gadgets
Getting Started
Adding the Developer Module
Alternatives for Hosting Gadgets
Creating a Gadget Spec
Defining Content
Defining User Preferences
Defining Gadget Preferences
Adding Homepage Gadgets to Other Google Properties
Where to Go From Here

Introduction

Audience

This document is intended for people who want to use the Google Gadgets API to write gadgets. Gadgets are so easy to create that they are a good starting point if you are just learning about web programming. The Google Gadgets API consists of a few simple building blocks: XML, HTML, and JavaScript. To get started, all you need is a basic understanding of HTML. We will teach you all you need to know about XML to write gadgets. Later, as you write more sophisticated gadgets, you will probably want to learn some JavaScript if you're not familiar with it already.

XML is a general purpose markup language. It describes structured data in a way that both humans and computers can read and write.

XML is the language you use to write gadget specifications. A gadget is simply an XML file, placed somewhere on the internet where Google can find it. The XML file that specifies a gadget contains instructions on how to process and render the gadget. The XML file can contain all of the data and code for the gadget, or it can have references (URLs) for where to find the rest of the elements.

HTML is the markup language used to format pages on the internet. The static content of a gadget is typically written in HTML.

JavaScript is a scripting language you can use to add dynamic behavior to your gadgets.

Note: Gadgets were formerly called modules, which is why the word "Module" appears throughout the API.

"Hello, World"

The easiest way to start learning about this API is to see an example. The following gadget simply displays the message "Hello, world!":

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
<ModulePrefs title="hello world example" />
<Content type="html">
<![CDATA[ Hello, world! ]]> </Content>
</Module>

You can see the actual gadget specification here.

Note the following about this example:

  • Gadgets are specified in XML. The first line is the standard way to start an XML file. This must be the first line in the file.
  • The <Module> tag indicates that this XML file contains a gadget.
  • The <ModulePrefs> tag contains information about the gadget such as its title, description, author, and other optional features.
  • The line <Content type="html"> indicates that the gadget's content type is HTML.
  • <![CDATA[ ...insert HTML here... ]]> is used to enclose HTML when a gadget's content type is HTML. It tells the gadget parser that the text within the CDATA section should not be treated as XML.
  • </Content> signifies the end of the Content section.
  • </Module> signifies the end of the gadget definition.

To run this example:

  1. Go to http://www.google.com/ig.
  2. To add a gadget, you must have a personalized homepage. If you don't already have one, you must create one by clicking Personalize your Google homepage. Then sign in with an existing Google Account, or create a new one.
  3. Once you have a personalized homepage, you can add gadgets to it by clicking Add content in the upper left corner. This takes you to the content directory. You can use the content directory to search for gadgets and add them to your homepage.
  4. Click Add by URL (next to the "Search Homepage Content" button).
  5. In the Add by URL text box, enter "hello.xml", and click Add.

The text "hello.xml" is shorthand for the URL http://www.google.com/ig/modules/hello.xml. You can put the URL for any gadget specification in the Add by URL text box, including ones that you or your friends write (as long as they are posted on a public web server).

Writing Your Own Gadgets

Getting Started

To get started writing your own gadgets, we recommend that you copy one of the examples and make a very simple change to it. For example:

  1. Copy the XML specification file (http://www.google.com/ig/modules/hello.xml) for Hello World to a public web server. If you don't have access to a public web server, you can use one of the available alternatives.
  2. Use a text editor to change the title and message. Don't forget to save the file when you're done.
    <?xml version="1.0" encoding="UTF-8" ?> 
    <Module>
      <ModulePrefs title="My first gadget" /> 
       <Content type="html"> 
         <![CDATA[ 
            <B>Welcome to my first gadget!</B> 
         ]]> 
       </Content> 
    </Module>
  3. Go to http://www.google.com/ig. If you don't already have a personalized homepage, you must create one as described above.
  4. Click Add content. This takes you to the content directory. You can use the content directory to search for gadgets and add them to your homepage.
  5. Click Add by URL (next to the "Search Homepage Content" button).
  6. In the Add by URL text box, type the URL for the XML gadget specification you want to add, and click Add. To figure out what this URL should be, you may have to ask for help from your webmaster.

Adding the Developer Module

The developer module acts a "command center" for all of the gadgets on your homepage. In addition to listing all the gadgets that you're running, it lets you add, view, and manage gadgets. The developer module gives you features that you will need if you're doing gadget development. For example, it lets you add gadgets that are "broken," which is useful when you are actively changing a gadget.

To add the developer module, click here: Add to Google

Developer Module

In the developer module you can click on individual gadget links to view their XML specifications. This is a good way to see how other gadgets are implemented.

You don't need to worry about advanced developer module features for now. They are discussed in more detail in Using the Developer Module. But one feature you may want to take advantage of right away is the Cached checkbox. By default, gadget specifications are cached. You should uncheck Cached for gadgets while you are working on them. This lets you see your edits instead of the cached gadget.

Alternatives for Hosting Gadgets

If you don't have access to a public web server, you can host your gadgets using Google Pages.

To host gadgets using Google Pages:

  1. Go to http://pages.google.com/ and log into your Google account.

    If you are a new Google Pages user: The first time you use Google Pages, you must agree to the Terms and Conditions before you can go any further. After that, you are taken to a page that displays your default Google Pages home page in an editor (note that this home page is not related to your personalized homepage). From this page you can click Back to the Page Manager to go to the Page Manager.

    If you are not a new Google Pages user: When you log into Google Pages, the first page it displays is the Page Manager.

  2. In the Page Manager, click the upload link (lower right corner).
  3. Type the full path of your gadget specification, or use the Browse button to upload the file to your Google Pages base directory. The added file is listed in the "Uploaded stuff" area of the Page Manager. You can delete files by clicking their associated trash can icons.
  4. Once you have uploaded your gadget specification, you can reference it using a URL relative to your Google Pages base directory.

For example, suppose you have a gadget called "myphonebook.xml," and you upload it to Google Pages. You could then add it to your personalized homepage with a URL such as the following:

http://<Google-username>.googlepages.com/myphonebook.xml

Remember: Gadgets are Public

Remember that there is no such thing as a private gadget. Once you publish your gadget on a public website, people can find it and view it. Be sure not to include personal information, such as your telephone number or personal email address.

What if you don't want your gadget to be public? Google encourages gadget authors to share their specifications. However, if you want to minimize your gadget's public visibility before you are ready to release it, here are some tips:

  • Don't submit your gadget to the content directory or post it to directories like googlemodules.com or hotmodules.com.
  • If people can't find your gadget, it's unlikely that they'll guess the URL. There are some subtleties to avoid getting crawled by search engines:
    • Make sure your web server doesn't provide a file listing that includes your file (this also avoids users snooping).
    • Make sure there are no web hyperlinks to your gadget.

Creating a Gadget Spec

Once you understand how to edit and publish gadgets, you're ready to include more advanced features in your gadget specifications. The XML gadget specification consists of 3 major parts:

  • Gadget Preferences. The <ModulePrefs> section in the XML file specifies characteristics of the gadget, such as title, author, preferred sizing, and so on.
  • User Preferences. The <UserPrefs> section defines controls that allow users to specify settings for the gadget. For example, a personalized greeting gadget might provide a text field for users to specify their names.
  • Content Section. The <Content> section is where the real work of your gadget happens. It is where you specify the type of gadget, your programming logic, and often the HTML elements that determine the appearance of your gadget.

When writing a gadget, you should start with the <Content> section.

Defining Content

The <Content> section represents the "brains" of a gadget. The <Content> section defines the type of content, and either holds the content itself or has a link to external content. The <Content> section is where the gadget attributes and user preferences are combined with programming logic and formatting information to become a running gadget.

The following table lists the <Content> attributes:

Attribute Description
type Optional string that gives the type of the content. The possible values are "html" and "url". The default is "html".
href String that provides a destination URL. Required for type="url", and not allowed for type="html".
cdata Optional string. For HTML, contains the raw HTML to render in the iframe.

For guidelines on which content type is right for your gadget, see Which Content Type Should I Use?

HTML Content

A gadget can have the type "html". This means that it contains HTML, possibly with embedded JavaScript, Flash, ActiveX, or other browser objects. The rules for an HTML gadget are as follows:

  • HTML must go within the CDATA section:
<Content type="html"> 
    <![CDATA[ HTML here... ]]>

CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup. The only delimiter that is recognized in a CDATA section is the "]]>" string that ends the CDATA section.

  • You cannot use the <html>, <head>, or <body> tags. Gadgets are generated with their own <html>, <head>, and <body> tags. Just include the content that would normally go inside the <body> tag.

Here is an example of a gadget that just uses HTML. This gadget displays a clickable photograph that opens a photo album in a new HTML page:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
    <ModulePrefs title="Go to Photo Album" height="250" scaling="false" />
    <Content type="html">
        <![CDATA[ 
          <div style="text-align:center">
<a id="Riggs" title="My Photo Album" target="_blank" href="http://picasaweb.google.com/doc.examples/ShelfBoy"> <img border="0" alt="Photo" src="http://static.photo-hosting-site.com/27/62190238_2210325e9d_m.jpg" title="Click Here."> </a> </div> ]]> </Content> </Module>

This is an example of the running gadget:

HTML Example

A gadget with an HTML content type can also reference an external JavaScript file:

<Module>
<ModulePrefs ... /> 
  <Content type="html"><![CDATA[
    <script src="http://www.example.com/gadgets/clock/clock.js" type="text/javascript"></script>
  ]]></Content> 
</Module>

URL Content

A gadget can have a URL content type. In this case the href= attribute provides a URL, and any other content in the gadget spec is ignored. With a URL content type, the assumption is that all information relating to the gadget's user interface and programmatic logic resides in the HTML file referenced by the URL. You do not put any HTML markup or JavaScript within the gadget itself. For example:

<Module>
  <ModulePrefs ... /> 
  <Content type="url" href="http://www/cgi-bin/example/gadgets/mystats.cgi" /> 
</Module> 

For a description of how to pass parameters between a url-type gadget and its target web page, see Getting User Prefs from URL-Type Gadgets.

By default, gadgets are displayed in iframes. Iframes include a transparent margin if you don't put in code to specify otherwise. Gadgets with the content type html are automatically generated with the appropriate code to remove margins. However, when your content type is URL, you are responsible for managing how your gadget is displayed. To remove margins, include the following text in the HTML file referenced by your gadget:

<style type="text/css"> body {margin: 0px;} </style>

You must properly escape the following characters in a type="url" gadget:

Character Escape Code
& &amp;
< &lt;
> &gt;
" &quot;

For example:

  • BAD: href="http://www.foo.com/bar?x=a&y=b"
  • GOOD: href="http://www.foo.com/bar?x=&amp;y=b"
  • BAD: description="this is a "sexy" gadget"
  • GOOD: description="this is a &quot;sexy&quot; gadget"

Which Content Type Should I Use?

The most flexible, versatile content type is html. Almost all of the examples in this developer guide use the html content type, because it lets you take advantage of the Google Gadgets JavaScript API and other specialized gadget features. The url content type imposes more restrictions on you.

The basic differences between the html and url types are as follows:

  • With an html content type, all of the content resides in the gadget spec. This includes HTML markup and JavaScript. You can use the Google Gadgets JavaScript API.
  • With a url content type, the only non-XML content in the gadget spec is the URL that links to a remote web page. The remote web page is where all of the HTML markup and JavaScript resides. You can NOT put any HTML markup or JavaScript code in the gadget spec itself. You also cannot use the Google Gadgets JavaScript API (though userprefs are appended to the URL, which lets you use them in your target web page). However, in spite of its limitations, the url content type may be the best choice if you are turning an existing application or webpage into a gadget, and you don't need to take advantage of specialized gadget features.

Defining User Preferences

Some gadgets need to give users a way of supplying user-specific information. For example, a game gadget might allow users to enter a preferred level of difficulty. The user preferences (<UserPref>) section in the XML file describes the user input fields that are turned into user interface controls when the gadget runs. User preferences are stored persistently.

For example, this gadget displays a personal greeting based on the time of day. It lets users specify the following:

  • A name to use in the greeting. The name is also displayed in the title bar.
  • A background color.
  • Whether to display a photo.

This is an example of the running gadget:

Sample Module

This is what the gadget looks like when the user clicks edit to modify the user preferences:

Userprefs Controls

The user preferences that get turned into user interface controls in the running gadget are defined in the XML specification as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Preferences for __UP_myname__" height="250" />
<UserPref name="myname" display_name="Name" required="true"/>
<UserPref name="myphoto" display_name="Photo"/>
<UserPref name="mychoice" display_name="Show Photo?" datatype="bool"/>
<UserPref name="mycolor" display_name="Color" default_value="Yellow" datatype="enum" >
   <EnumValue value="Red" />
   <EnumValue value="Aqua" />
   <EnumValue value="Lime" />
   <EnumValue value="Yellow" />
   <EnumValue value="Pink" />
   <EnumValue value="Orange" />
   <EnumValue value="White" />
</UserPref> 

Note the following:

  • Line 3 of the file contains the text title="Preferences for __UP_myname__". When you run the gadget, the value supplied for the user preference myname is dynamically substituted for __UP_myname__.
  • The myname user preference is marked as "required." If the user tries to run the gadget without supplying a value for this field, the user preferences editing box remains open until a value is provided.
  • The user preference mychoice has a bool data type. This is displayed in the user interface as a checkbox.
  • The user preference mycolor has an enum data type. The list of EnumValues specifies the choices that appear in a drop-down menu in the user preferences editing box.

Here is the JavaScript that displays the greeting for the gadget. For a discussion of the use of __MODULE_ID__ at the end of the sample code, see the section Writing Robust Gadgets:

<Content type="html"><![CDATA[
<script type="text/javascript">
function displayPersonalGreeting (prefs) {
// Get current time
var today = new Date();
var time = today.getTime();

// Based on the time of day, display an appropriate greeting
var hour = today.getHours();
var salutation = "Afternoon";
if (hour < 12) {
salutation = "Morning";
} else if (hour > 17) {
salutation = "Evening";
} // Set the background color according to the mycolor userpref document.body.style.backgroundColor = prefs.getString("mycolor"); // Display a greeting based on the myname userpref document.write("<br><FONT SIZE=6>Good " + salutation + ", " + prefs.getString("myname") + "!!!<br><br></FONT>"); // If the "Show Photo?" checkbox is checked, display photo. if (prefs.getBool("mychoice") == true) { document.write('<img src="' + prefs.getString("myphoto") + '">'); } } // Pass the userprefs for this gadget instance to the function // (allows users to include multiple gadget instances on their page) displayPersonalGreeting(new _IG_Prefs(__MODULE_ID__)); </script> ]]> </Content>

For a list of all the <UserPref> attributes, see the Reference.

User preferences can be accessed from your gadget using the user preferences JavaScript API, for example:

<script type="text/javascript">
  // Must be constructed using the __MODULE_ID__ token. It gets replaced
  // at runtime with the actual ID of your gadget.
  var prefs = new _IG_Prefs(__MODULE_ID__);
  var someStringPref = prefs.getString("StringPrefName");
  var someIntPref = prefs.getInt("IntPrefName");
  var someBoolPref = prefs.getBool("BoolPrefName");
</script>

For a list of all of the JavaScript functions, see the Reference.

User Preference Substitution Variables

You can use a substitution variable of the format __UP_userpref__ in the <ModulePrefs> or <UserPref> sections, where userpref matches the name attribute of a user preference. When the gadget runs, the string value of the corresponding user preference is substituted for the variable, unescaped. For example, in this excerpt, the value the user supplies at run time for the projects user preference is substituted for __UP_projects__ in the title_url string:

<Module>
<ModulePrefs title="Build Monitor"
             title_url="http://www.example.com/build/status.php?__UP_projects__"/>
<UserPref name="projects" display_name="project(s)"/>
<Content ... />
</Module>

You can see another example of this in the user preferences sample.

Here are the general guidelines for using user preference substitution variables:

  • For the <ModulePrefs> title attribute, use __UP_name__ . This is HTML-escaped.
  • For the <ModulePrefs> title_url attribute, use __UP_name__ . This is URL-escaped.
  • In HTML within the <Content> section , use __UP_name__ . This is HTML-escaped.
  • In JavaScript code within <Content> section, use the _IG_Prefs() function.

Using the "location" Data Type

Gadgets based on Google Maps can use the location data type. The following example gadget illustrates how to use the location data type. For gadgets, the value supplied for a location data type must be a major city or postal code in the United States, Canada, or the United Kingdom. You might find that using postal codes yields a better result.

When you use the location data type, you can use getString() to retrieve the longitude and latitude of the user-specified location.

<Module>
<ModulePrefs title="Map of __UP_loc__" height="300" author="Jane Smith" author_email="xxx@google.com" />
<UserPref name="loc" display_name="Location" datatype="location" required="true" />
<Content type="html">
<![CDATA[
<script src="http://maps.google.com/maps?file=js" type="text/javascript"></script>
<div id="map" style="width: 100%; height: 100%;"></div>
<script type="text/javascript">
var prefs = new _IG_Prefs(__MODULE_ID__);
var map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.centerAndZoom(new GPoint(prefs.getString("loc.long"), prefs.getString("loc.lat")), 6);
</script> ]]> </Content> </Module>

When reading a location preference x:

  • If x is the empty string (signifying an empty location), x.lat and x.long are the empty string.
  • If x couldn't be geocoded (signifying an invalid location), x.lat and x.long are 0.0.

Earlier versions of the Google Gadgets API did not allow you to specify a default_value for a location type. This is no longer the case.

Defining Gadget Preferences

The <ModulePrefs> section in the XML file specifies characteristics of the gadget, such as title, author, preferred sizing, and so on. For example:

<Module>
<ModulePrefs title="Today's Network Traffic" title_url="http://www/~rowan/gadgets/stats/"
height="200" author="Jane Smith" author_email="xxx@google.com"/>
<Content ...>
... content ...
</Content>
</Module>

The users of your gadget cannot change these attributes.

For a full list of the <ModulePrefs> attributes, see the Reference.

Adding Homepage Gadgets to Other Google Properties

The personalized homepage is not the only Google product that supports gadgets. You can also add homepage gadgets to Google Desktop and Google Pages (still experimental).

Compatibility

You can add most homepage gadgets to Google Desktop and Google Pages. However, homepage gadgets are not completely interchangeable with Desktop and Pages gadgets. Here are some of the limitations:

  • You cannot add Desktop gadgets to the personalized homepage.
  • You cannot add inlined homepage gadgets to the Desktop or to Google Pages.
  • Google Pages does not expose a gadget's title bar or user preferences except within the Pages editor. In a running gadget on a Google Pages webpage, the title bar and user preferences are not visible or accessible. This could affect your gadget design as well as the types of gadgets you choose to add to Pages.
  • To add homepage gadgets to Desktop or Pages, you go to those products' content directories and add the gadget by its gadget spec URL, as described below.

Adding Homepage Gadgets to Google Desktop

To add a homepage gadget the Desktop via the Desktop Sidebar:

  1. At the top of the Sidebar, click Add.
  2. Type the URL for a homepage gadget spec into the Search gadgets text field and then click Search gadgets. If the gadget is found, its title is displayed next to an Add button. Click Add.

Adding Homepage Gadgets to Google Pages

Note: Gadgets are still considered an experimental feature in Google Pages. To enable them, choose Site settings (upper right corner) in the Page Manager. On the Settings page, click Enable experimental features. Then click Yes.

To add a homepage gadget to Google Pages:

  1. From the Page Manager, open a page in the editor.
  2. Put the cursor in the field to which you want to add the gadget.
  3. Click More.
  4. In the Add a Gadget dialog, choose Third party gadgets to display a text field where you can type the URL for a gadget spec. Enter the URL and click Add Gadget. This takes you into a preview screen. From there, click OK to confirm the addition.
  5. Back in the editor you can drag the gadget to position it. When you are finished, click Publish.

Where to Go From Here

For a description of advanced programming tasks, see Part 2 of the Developer Guide.