Skip to content
vohtaski edited this page Apr 5, 2012 · 12 revisions

Introduction

We show here how to use OpenSocial API when implementing gadgets for Moodle (or in general for OpenSocial). We only target JavaScript APIs that you would use in your gadget. In general, you should follow the API specified in OpenSocial spec. However, there are also few requests that are specific to Space extension. We will point them out!

Sample gadget

This a very simple gadget that uses OpenSocial API. It retrieves the person viewing the gadget and shows his name.

<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs title="OS viewer with JavaScript">
    <Require feature="osapi"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[
      <div id="viewer"></div>
  
      <script type="text/javascript">
        var initialize = function() {
          osapi.people.getViewer().execute(function(viewer){
            document.getElementById('viewer').innerHTML = "Hello "+viewer.id+"!";
          });
        };
      </script>

      <script type="text/javascript">
        gadgets.util.registerOnLoadHandler(initialize);
      </script>
  
    ]]>
  </Content>
</Module>

APIs

Get user who looks at widget at the moment

osapi.people.getViewer().execute(function(viewer){
  viewer.id;
  viewer.displayName;
});

Get the owner of the course where widget lives

osapi.people.getOwner().execute(function(owner){
  owner.id;
  owner.displayName;
});

Get more information about the person with id="1"

osapi.people.get({userId: "1", groupId: "@self"}).execute(function(owner){
  owner.id;
  owner.displayName;
});

[Extension] Get the widgetspace where widget lives

osapi.context.get().execute(function(context){
  context.contextId; // id of the widgetspace
});

[Extension] Get more information about the widgetspace with id="1"

osapi.spaces.get({contextId: "1"}).execute(function(response){
  var widgetspace = response[0];
  widgetspace.displayName;
  widgetspace.profileUrl;
  widgetspace.parentId;  // Id of the course where widgetspace lives
});

[Extension] Get information about the widget itself

osapi.apps.get({contextId:"@self"}).execute(function(app){
  app.appURL;
  app.thumbnailUrl;
});

Save appdata (key-value pair) for the course with id="1"

// [Extension] we have to add prefix "s_" to context variable: 
// context = "s_1"
osapi.appdata.update({userId: context, data: {key: value}).execute(function(){   
});

Get appdata for the course with id="1"

// [Extension] we have to add prefix "s_" to context variable: 
// context = "s_1"
osapi.appdata.get({userId:"s_1", keys: ['key']).execute(function(data){
  data[context]['key'];
});