English | Site Directory

Writing Your Own Gadgets

Getting Started introduces you to gadgets. The next step is creating your own gadgets. This document tells you how.

Contents

  1. Basic Steps
  2. Anatomy of a Gadget
    1. Defining Content
    2. Defining User Preferences
    3. Defining Gadget Preferences
  3. Remember: Gadgets are Public
  4. Where to Go From Here

Basic Steps

Here are the basic steps you follow to create and deploy a gadget:

  1. Use any text editor to write your gadget specification, and host it on a public web server.
  2. Add your gadget to a container, such as iGoogle or Orkut. A container is an application or site that has the ability to run gadgets.

Anatomy of a Gadget

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:

  • 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.
  • 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.
  • Gadget Preferences. The <ModulePrefs> section in the XML file specifies characteristics of the gadget, such as title, author, preferred sizing, and so on.

Note: Within the XML attributes in a gadget spec, you need to "escape" (that is, properly encode) certain characters so that they will be interpreted correctly. For more information, see Escaping Special Characters.

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 easiest way to create your gadget is to simply place HTML (and optionally, JavaScript or Flash) into the <Content> section. Experienced web developers can read Choosing a Content Type for other options relating to access control, remote hosting, using alternative scripting languages, and other topics. Here's a simple sample gadget. 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://doc.examples.googlepages.com/Riggsie-OP.jpg"
title="Click Here."></a>
</div> ]]> </Content> </Module>

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 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" default_value="http://doc.examples.googlepages.com/rowan-headshot.jpg"/>
<UserPref name="mychoice" display_name="Show Photo?" datatype="bool" default_value="true"/>
<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 edit 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 edit box.

Here is the complete gadget, including the JavaScript that displays the greeting for the gadget:

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="Preferences for __UP_myname__" height="400"/> 
  <UserPref name="myname" display_name="Name" default_value="Rowan"/>
  <UserPref name="myphoto" display_name="Photo" default_value="http://doc.examples.googlepages.com/rowan-headshot.jpg"/>
  <UserPref name="mychoice" display_name="Show Photo?" datatype="bool" default_value="true"/>
  <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>
   <Content type="html"><![CDATA[
   <div id="content_div"></div>
   <script type="text/javascript">
   // Get userprefs
   var prefs = new gadgets.Prefs();

   function displayGreeting () {
     // Get current time
     var today = new Date();
     var time = today.getTime();
     var html = "";
  
     // 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
     var element = document.getElementById('content_div');  
     element.style.height=250;
     // Set the background color according to the mycolor userpref   
     element.style.backgroundColor=prefs.getString("mycolor"); 

     // Display a greeting based on the myname userpref
     html += "<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) {
       html += '<img src="' + prefs.getString("myphoto") + '">';
     }
     element.innerHTML = html;
   }
   // Pass the userprefs for this module instance to the function
   // (allows users to include multiple module instances on their page)
   gadgets.util.registerOnLoadHandler(displayGreeting); 
  
   </script> 
   ]]>  
  </Content>
</Module>

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

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

<script type="text/javascript">
  var prefs = new gadgets.Prefs();
  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 JavaScript 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 gadgets.Prefs() function.

Sharing User Preferences

You can use the shareable-prefs feature to make it possible for a gadget's user preferences to be edited by multiple users. Thus, users can share the gadget and see each other's edits. For example, family members could share a grocery list gadget, with each person adding his or her favorite items. User preference data is the part of the gadget state that is hosted by iGoogle. For more information about userprefs, see the Gadgets API Developers Guide.

To share a gadget's userprefs across multiple users, the gadget must include the line <optional feature="shareable-prefs"/> in the <ModulePrefs> section. For example, this gadget uses the list data type userpref to populate a grocery list:

Sharing this gadget

Here is the code for the gadget:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs 
    title="Our Grocery List" 
    scrolling="true"> 
    <optional feature="shareable-prefs"/> 
   </ModulePrefs>
  <UserPref name="mylist" 
    display_name="Add items" 
    datatype="list" />
  <Content type="html">
  <![CDATA[ 
    <div id="content_div" style='color: #CC0099; font-family: serif; font-size: 120%;'></div>

  <script type="text/javascript"> 
    // Get userprefs
    var prefs = new gadgets.Prefs();
    // Get the list
    var items = prefs.getArray("mylist");  
    var html = "";
    // If there are no items in the list yet, display message.
    if (items.length == 0)
    {
      html += "Edit the userprefs to add items to the list.";
    }
    else {
      for (var i = 0; i < items.length ; i++) {
        var term = (items[i]);
        html += term + "<br />";
      }
    }
    document.getElementById("content_div").innerHTML = html; 
  </script>
  ]]> 
  </Content>
</Module>

Once you have added a gadget that supports shareable prefs to iGoogle, you can make it collaborative, as follows.

Step 1: Click the triangle on the gadget you want to share and choose Share this gadget.

Sharing this gadget

Step 2: If you're a Gmail user, pick the friends you want to share with or type in their email addresses.

Sharing this gadget

Step 3: Decide whether you want to let your friends edit your gadget content or just view it on their iGoogle page.

  • If you pick View and edit my content, your friends can edit the gadget's userprefs. Their changes will be reflected in your version of the gadget and any other shared versions of the gadget.
  • If you pick View my content, your friends cannot modify the gadget, not even their local copies. Only you can modify the gadget, and your changes will be pushed to all shared versions of the gadget.

Click Send Invites. Your friends get an email from you inviting them to add the gadget it to their own iGoogle page.

Sharing invitation

Friends that you've authorized to edit the gadget can then modify the gadget's userprefs and publish their changes to all shared versions of the gadget.

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.

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

Where to Go From Here

When you're ready to write more complex gadgets, go to Development Fundamentals, or back to the documentation home page for an overview of sections and topics.

Back to top