SEARCH
Newsletter
Subscribe to get design tips, latest trends, free stuff and more.
It doesn't look like an e-mail address

hosting

  Tutorials HTML and CSS Tutorials Creating OpenSocial Gadgets

Creating OpenSocial Gadgets

There are two things which look and act similar but are different, gadgets and widgets.

Widgets can be referred to any icons or graphical interface element that is operated by a computer or internet use to execute a preferred function online or on the computer. You can add a widget in all kind of web pages.

A gadget acts just like a widget, often fulfilling the same purpose, but it is proprietary or called to be self-contained. It only works on a certain website or a specific set of websites. For example, OpenSocial Gadgets can look and act like widgets. But they only work on OpenSocial enabled web pages.

You can use gadgets to make your web pages even more interesting and useful to your visitors. People can add your gadget to their personalized profile pages or to their other pages.

OpenSocial gadgets also work in very similar way like a normal gadget plus the gadgets have unlimited ways to bring new functionalities through incorporating customized code into service classes of Shindig. In this tutorial, we will explore more about OpenSocial gadgets. Please note that I am assuming that either you have a OpenSocial integrated website where you would like to use gadgets or you want to contribute the gadget to the gadget directory. The gadgets will not work on any website.

OpenSocial Gadgets

Gadgets are applications and you can build gadgets according to your unique requirements. Otherwise just use existing gadget from reliable directories and customize it for the field names etc. to make it work on your website.

At their core, social gadgets are XML files, sometimes known as gadget specifications. Here is a simple "Hello World" gadget (helloworld.xml) that illustrates the basic sections of a specification:

<?xml version="1.0" encoding="UTF-8" ?>
 <Module>
   <ModulePrefs title="Hello World!">
     <Require feature="opensocial-0.8" />
   </ModulePrefs>
   <Content type="html">
     <![CDATA[
       Hello, OpenSocial Gadget world!
     ]]>
   </Content>
 </Module>

In the "Hello OpenSocial Gadget world " example, you can see several sections which control the features and design of the gadget. A gadget is hosted in a server infrastructure to provide its data.

<Module> indicates that this XML file contains a gadget. It is a root tag. This root tag contains a <ModulePrefs> and a <Content> section.

<ModulePrefs> is in XML format. It specifies characteristics of the gadget, such as title, author, preferred sizing, and so on.

<Require feature="opensocial-0.8" /> denotes a required feature of the gadget - in this case, the OpenSocial API (v0.8).

<Content type="html"> indicates that the gadget's content type is HTML. This is the recommended content type for OpenSocial containers, but gadgets for other containers such as iGoogle support other content types.

<![ CDATA[a:...]]> contains the bulk of the gadget, including all of the HTML, CSS, and JavaScript (or references to such files). The content of this section should be treated like the content of the body tag on a generic HTML page.

We usually have one more tag of <UserPrefs> section, which 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. The gadgets API consist of a few simple building blocks: XML, HTML, and JavaScript. So writing your own gadgets are not difficult once we understand few basics.

Giving Gifts Gadget Description

One example to access your friend's list is below, let's build to complete virtual gift giving functionality for your website. To access the example, visit the link http://opensocial-resources.googlecode.com/svn/samples/tutorial/tags/api-0.8/gifts_2_send_gifts.xml

Explanation of the above link code is follows:

The JavaScript function will allow you to select a friend to receive a virtual gift. Please check that using variable like "viewerFriends" is an undefined standard followed in the gadget community. OpenSocial defines two personas, the owner and the viewer. The owner is the user that owns the content on a particular page while the viewer is the logged in user looking at a page.

For example, if Alice is logged into a social network and she's viewing Bob's profile page, then Alice is the viewer and Bob is the owner. If Alice is viewing her own profile page then she is the owner and the viewer.

It's also possible for Alice to view Bob's instance of an application. Suppose Alice is viewing an app on Bob's profile and clicks a link that takes her to the canvas view. In this case, Alice is the viewer of the canvas view, and Bob is the owner. If Alice is viewing her own instance of an app's canvas page, then she is the owner and the viewer. The latter case, where owner == viewer, is often used to let the user configure the settings of an app.

Also note that to use this gadget you need to have a website where friend's functionality exists. Not every information oriented website has making friends online functionality, so they can use some other type of gadgets.

function onLoadFriends(data) {
  var viewer = data.get('viewer').getData();
  var viewerFriends = data.get('viewerFriends').getData();

  html = new Array();
  html.push('<select id="person">');
  viewerFriends.each(function(person) {
    if (person.getId()) {
      html.push('<option value="', person.getId(), '">', person.getDisplayName(), '</option>');
    }
  });
  html.push('</select>');
  document.getElementById('friends').innerHTML = html.join('');
}

Next, you'll need to create another selection menu of gifts you can give. The sample uses a selection of different types of nuts, but you can feel free to use whatever you like. A small update to the initialization function calls this function when the page loads.

var globalGiftList = ['a cashew nut', 'a peanut', 'a hazelnut', 'a red pistachio nut'];

function makeOptionsMenu() {
  var html = new Array();
  html.push('<select id="nut">');
  for (var i = 0; i < globalGiftList.length; i++) {
    html.push('<option value="', i, '">', globalGiftList[i], '</option>');
  }
  html.push('</select>');
  document.getElementById('gifts').innerHTML = html.join('');
}

function init() {
  loadFriends();
  makeOptionsMenu();
}

To tie all of this together, implement giveGift, the function called when a user clicks the "Give!" button in the gadget. The function loads the gift to be given and the friend to give it to, from the form, updates a global object of gifts, and saves this to the persistent storage.

var globalGivenGifts = {};

function giveGift() {
  var nut = document.getElementById('nut').value;
  var friend = document.getElementById('person').value;

  globalGivenGifts[friend] = nut;
  var json = gadgets.json.stringify(globalGivenGifts);

  var req = opensocial.newDataRequest();
  req.add(req.newUpdatePersonAppDataRequest("VIEWER", 'gifts', json));
  req.send();
}

The best way to kick off this article is with a quick overview of the opensocial.DataRequest class, which, in low-level terms, represents an HTTP request. It's imperative to understand that an {{opensocial.DataRequest}} object is not a request for OpenSocial data instead, one or more data requests (e.g. fetch person and fetch people requests) can be "attached" to the object. In this way, you can retrieve all of the information you need by sending out a single HTTP request instead of firing multiple asynchronous requests and handling their responses individually.

To create a new DataRequest object, use the newDataRequest() method under the opensocial namespace:

var req = opensocial.newDataRequest();

Fetch person requests are created by calling your opensocial.DataRequest object's newFetchPersonRequest() method, passing in an ID string or constant and, optionally, an object specifying pertinent parameters such as the extended profile fields to return with the person. The ID argument can be the OWNER or VIEWER constants discussed above a single OpenSocial ID string. After the request is sent, the API should return an opensocial.Person object representing the specified individual.

Here is the full code listing for a simple request for the application's owner. Notice that the 'owner' key has been passed with the fetch person request so that the retrieved profile information can be accessed in the callback function as described above. Also note that the function fetchPersonHandler() will be executed automatically when the response is ready.

var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER), 'owner');
req.send(fetchPersonHandler);

There are many functions which can be used directly and you will know more when you read shindig files. If you want to build your own OpenSocial apps, please refer the link http://docs.opensocial.org/display/OSD/Building+OpenSocial+Apps

OpenSocial gadgets help users share their activities with each other and access information about their friends. There are three main feature areas in the OpenSocial API:

People and relationships. Members of social networks have friends. OpenSocial applications use the connections between people and their friends.

Persistence. OpenSocial applications can take advantage of persistence, the ability to store data that can be retrieved when the application runs again at a later time.

Activities. People use social applications to inform others about what they're doing: going to a movie, posting photos, and so on.

HTML Page

The HTML page will be Apache Shindig sample container. OpenSocial apps can define multiple views to generate UI appropriate for the context in which the app is being shown. For example, you can define a profile view to be shown when the app is rendered on a user's profile. The other common view on a typical social network is the canvas view, which is used to render a full page view of the app. You can define the type of view both in an HTML page and in the XML file.

The gadget XML file defines two content sections, one for the profile view and one for the canvas.

<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs title="Social Mashup Tutorial - Gifts (simple views)">
  </ModulePrefs>
  <Content type="html" view="profile">
    <![CDATA[
      Hello, Gifts! (profile view)
    ]]>
  </Content>
  <Content type="html" view="canvas, default">
    <![CDATA[
      Hello, Gifts! (canvas view)
    ]]>
  </Content>
</Module>

Note that you can define multiple views for each content section, as well as declare a default for containers to use when they don't support the other views you've defined.

For simple HTML page you would use:

<!DOCTYPE html>
<html>
<head>
<title>Sample: Simple Container</title>
<!-- default container look and feel -->
<link rel="stylesheet" href="/img_articles/21466/gadgets.css">
<script type="text/javascript" src="/img_articles/21466/json.js"></script>
<script type="text/javascript" src="http://www.google.com/ig/ifpc.js"></script>
<script type="text/javascript" src="/img_articles/21466/cookies.js"></script>
<script type="text/javascript" src="/img_articles/21466/gadgets.js"></script>
<script type="text/javascript">
var specUrl0 = 'http://opensocial-resources.googlecode.com/svn/samples/tutorial/tags/api-0.8/gifts_2_send_gifts.xml;

// This container lays out and renders gadgets itself.

function renderGadgets() {
  var gadget0 = gadgets.container.createGadget({specUrl: specUrl0});

  gadgets.container.addGadget(gadget0);
  gadgets.container.addGadget(gadget1);
  gadgets.container.layoutManager.setGadgetChromeIds(
      ['gadget-chrome-x', 'gadget-chrome-y']);

  gadgets.container.renderGadget(gadget0);

};
</script>
</head>
<body onLoad="renderGadgets()">
  <h2>Sample: Simple Container</h2>
  <div id="gadget-chrome-x" class="gadgets-gadget-chrome"></div>
  <div id="gadget-chrome-y" class="gadgets-gadget-chrome"></div>
</body>
</html>

ABOUT THE AUTHOR

Developer Drive is a quality Web development blog featuring tutorials, tips, news and reviews on things that matter to developers. We cover the latest trends and techniques such as CSS3, HTML5, WordPress, responsive/mobile design and much more.

subscribe to newsletter