You are here: Docs Technical Documentation Clearspring APIs In-Widget API Context

Context

Run-time Intelligence

context provides run-time context to your widget, answering questions like "Where is this placement located?" and "How many times has the current visitor seen this widget?" All contextual variables are session-dependent--constant while the session is running, but not necessarily constant across sessions.

It also provides a set of methods under context.user.geo for getting information about the user's estimated world location. (Note that if our server-side lookup takes more than a few milliseconds, we cancel it to prevent degradation of service. This occurs in just under a fifth of all sessions.)

 

Contents

 

API Reference

Name Type Description
context.CAPABILITIES bitfield Capabilities of running placement host
context.DOMAIN string Placement domain
context.SERVICE string Placement domain's service code
context.URL string Placement URL
context.placement.CHILDREN integer Number of children of this placement
context.placement.CONFIGURATION object Mapping of placement parameter keys to values
context.placement.ID string Unique placement identifier
context.widget.CHILDREN integer Total number of child placements for this widget
context.widget.ID string Unique widget identifier
context.user.HAS_PLACED boolean True iff. the current user has ever placed the running widget themselves
context.user.IS_OWNER boolean True iff. the current user owns the running placement
context.user.WIDGET_VIEWS integer Number of times the current user has viewed this widget (across all placements)
context.user.PLACEMENT_VIEWS integer Number of times the current user has viewed this placement
context.user.geo.getCountry method ISO-3166 country code
context.user.geo.getContinent method Continent code
context.user.geo.getRegion method ISO-3166-1 region code
context.user.geo.getZIP method 5-digit ZIP
context.user.geo.getLatLon method Latitude/longitude tuple ({lat: [float], lon: [float]})
context.user.geo.getNetwork method Estimated connection mode (dialup, DSL, cable, ISDN)

context.CAPABILITIES

bitfield

The capabilities of the environment in which the running widget is embedded. If environment is unknown, CAPABILITIES will be undefined.

Bits to check:

Name Description
context.LINKOUT set iff. direct links offsite are allowed; if false, in Flash you'll have to make the user copy and paste links manually into their Web browser. In other words, if this is true, allowNetworking has been set to internal or none
context.OPENSOCIAL set iff. the host environment supports the OpenSocial APIs
context.TRANSPARENCY set iff. the host environment will properly render transparent widgets

Example Usage

AS2

if (_level0.cs.context.CAPABILITIES & _level0.cs.context.LINKOUT) {
	writeLink();		
} else {
	showLinkForCopyingAndPasting();
}

AS3

if (_api.context.CAPABILITIES & _api.context.LINKOUT) {
	writeLink();		
} else {
	showLinkForCopyingAndPasting();
}

JavaScript

// Note: Not available in JS container

if (_api.context.CAPABILITIES & _api.context.LINKOUT) {
	writeLink();		
} else {
	showLinkForCopyingAndPasting();
}
back to table

context.DOMAIN

string

The domain (if known) in which the running widget is embedded. If domain is unknown, DOMAIN will be undefined. All views of placements created through our sharing services will have this property set; roughly 80% of the remainder views will as well (it depends on a combination of browser, OS, Flash player version, and end-user configuration).

Example Usage

AS2

if (_level0.cs.context.DOMAIN == 'myspace.com') {
	// show myspace-specific content here
}

AS3

if (_api.context.DOMAIN == 'myspace.com') {
	// show myspace-specific content here
}

JavaScript

// Note: Not available in JS container

if (_api.context.DOMAIN == 'myspace.com') {
	// show myspace-specific content here
}
back to table

context.SERVICE

string

The service code (as used in menu.show()) given for the running placement's domain, if applicable (i.e., if the widget was placed on a site that we don't support with explicit sharing, context.SERVICE is undefined). Otherwise undefined at the same rate as context.DOMAIN.

Example Usage

AS2

// Open service menu to the current running site's 
// sharing UI; if we're not on a supported site, this 
// will just pop open the menu at its splash screen
_level0.cs.menu.open(_level0.cs.context.SERVICE);

AS3

// Open service menu to the current running site's 
// sharing UI; if we're not on a supported site, this 
// will just pop open the menu at its splash screen
_api.menu.open(_api.context.SERVICE);

JavaScript

// Note: Not available in JS container
//
// Open service menu to the current running site's 
// sharing UI; if we're not on a supported site, this 
// will just pop open the menu at its splash screen
_api.menu.open(_api.context.SERVICE);
back to table

context.URL

string

The URL used (if known) to access the page in which the running widget is embedded.

Example Usage

AS2

if (_level0.cs.context.URL.indexOf("cnn.com/offbeat")) {
	trace("We made offbeat news! Dreams really do come true.");	
}

AS3

if (_api.context.URL.indexOf("cnn.com/offbeat")) {
	trace("We made offbeat news! Dreams really do come true.");	
}

JavaScript

// Note: Not available in JS container

if (_api.context.URL.indexOf("cnn.com/offbeat")) {
	// Note #2: Actually alerting this on every page load while
	// on the CNN domain is not endorsed by Clearspring and may
	// be hazardous to the success of your widget
	alert("We made offbeat news! Dreams really do come true.");	
}
back to table

context.placement.CHILDREN

integer

See this topic for an explanation of our "widget" versus "placement" terminology and an overview of placement inheritance.

The number of placements generated from the running placement. If a user viewing this placement decided to grab it for their own page, the resulting placement is considered a child.

Example Usage

AS2

if (_level0.cs.context.placement.CHILDREN > 10) {
	// this is an influential placement
	showGoldStar();
}

AS3

if (_api.context.placement.CHILDREN > 10) {
	// this is an influential placement
	showGoldStar();
}

JavaScript

// Note: Not available in JS container

if (_api.context.placement.CHILDREN > 10) {
	// this is an influential placement
	showGoldStar();
}
back to table

context.placement.CONFIGURATION

object

Object mapping configuration parameter keys to values.

Example Usage

AS2

// Let's say we set up a parameter in Clearspring console
// called 'color' whose default was 'red'.
// 'config' in the sample below would be the object {color: 'red'}
var config:Object = _level0.cs.context.placement.CONFIGURATION;

// If we were to configure a particular placement during a share
// (see http://www.clearspring.com/docs/tech/apis/in-widget/share#share.put)
// to have the color 'green', config would be {color: 'green'} when
// viewed on that placement.

AS3

// Let's say we set up a parameter in Clearspring console
// called 'color' whose default was 'red'.
// 'config' in the sample below would be the object {color: 'red'}
var config:Object = _api.context.placement.CONFIGURATION;

// If we were to configure a particular placement during a share
// (see http://www.clearspring.com/docs/tech/apis/in-widget/share#share.put)
// to have the color 'green', config would be {color: 'green'} when
// viewed on that placement.

JavaScript

// Note: Not available in JS container

// Let's say we set up a parameter in Clearspring console
// called 'color' whose default was 'red'.
// 'config' in the sample below would be the object {color: 'red'}
var config:Object = _api.context.placement.CONFIGURATION;

// If we were to configure a particular placement during a share
// (see http://www.clearspring.com/docs/tech/apis/in-widget/share#share.put)
// to have the color 'green', config would be {color: 'green'} when
// viewed on that placement.
back to table

context.placement.ID

string

Unique identifier for this placement (set by Clearspring). Useful for correlating placement data using a server-side application. Without an identifier maintained by us, you could easily correlate data across all placements, or for one user (using cookies), but not for a specific placement.

Example Usage
var pid:String = _level0.cs.context.placement.ID;
var lv:LoadVars = new LoadVars();
lv.pid = pid;
lv.send("http://example.org/process", "POST");
back to table

context.widget.CHILDREN

integer

See this topic for an explanation of our "placement" versus "widget" terminology and an overview of widget inheritance.

The total number of placements of the running widget, across all domains and platforms.

Example Usage

AS2

if (_level0.cs.context.widget.CHILDREN == 50000) {
	// our viral campaign is a success!
	mail("me@example.org", "aketay the oneymay and unray.")
}

AS3

if (_api.context.widget.CHILDREN == 50000) {
	// our viral campaign is a success!
	mail("me@example.org", "aketay the oneymay and unray.")
}

JavaScript

if (_api.context.widget.CHILDREN == 50000) {
	// our viral campaign is a success!
	mail("me@example.org", "aketay the oneymay and unray.")
}
back to table

context.widget.ID

string

Unique identifier for this widget (determined by Clearspring at registration-time).

Example Usage

AS2

var wid:String = _level0.cs.context.widget.ID;
var lv:LoadVars = new LoadVars();
lv.wid = wid;
lv.send("http://example.org/process", "POST");

AS3

var wid:String = _api.context.widget.ID;
var myRequest:URLRequest = new URLRequest("http://example.org/proces");
myRequest.method = URLRequestMethod.POST;
myRequest.data = {widgetId: wid};

var receiver:URLLoader = new URLLoader();
receiver.load(myRequest);

JavaScript

// Note: Not available in JS container

var wid:String = _api.context.widget.ID;
alert('My unique Clearspring ID: ' + wid);
back to table

context.user.HAS_PLACED

boolean

True if and only if the user has placed this widget somewhere.

Example Usage

AS2

if (_level0.cs.context.user.HAS_PLACED) {
	giveLoyalCustomerDiscount();
	showCoolerArtwork();
}

AS3

if (_api.context.user.HAS_PLACED) {
	giveLoyalCustomerDiscount();
	showCoolerArtwork();
}

JavaScript

// Note: Not available in JS container

if (_api.context.user.HAS_PLACED) {
	giveLoyalCustomerDiscount();
	showCoolerArtwork();
}
back to table

context.user.IS_OWNER

boolean

True if and only if the user has placed this widget somewhere.

Example Usage

AS2

if (_level0.cs.context.user.IS_OWNER) {
	showVoteResults();
} else {
	showVoteUI();
}

AS3

if (_api.context.user.IS_OWNER) {
	showVoteResults();
} else {
	showVoteUI();
}

JavaScript

// Note: Not available in JS container

if (_api.context.user.IS_OWNER) {
	showVoteResults();
} else {
	showVoteUI();
}
back to table

context.user.WIDGET_VIEWS

integer

Number of times the current visitor has viewed this widget, across all placements.

Example Usage

AS2

var uwv:String = _level0.cs.context.user.WIDGET_VIEWS;
if (umw > 100 && !_level0.cs.context.user.HAS_PLACED) {
	displayMessage("Wow, you really like this widget! " +
	   	       "You've viewed it over "+umv+" times. Why don't you get your own?");
}

AS3

var uwv:String = _api.context.user.WIDGET_VIEWS;
if (umw > 100 && !_api.context.user.HAS_PLACED) {
	displayMessage("Wow, you really like this widget! " +
	   	       "You've viewed it over "+umv+" times. Why don't you get your own?");
}

JavaScript

// Note: Not available in JS container

var uwv= _api.context.user.WIDGET_VIEWS;
if (umw > 100 && !_api.context.user.HAS_PLACED) {
	displayMessage("Wow, you really like this widget! " +
	   	       "You've viewed it over "+umv+" times. Why don't you get your own?");
}
back to table

context.user.PLACEMENT_VIEWS

integer

Number of times the current visitor has viewed the running placement.

Example Usage

AS2

var upv:String = _level0.cs.context.user.PLACEMENT_VIEWS;
var date:Date = new Date();
if (upv > 10000 && date.getMonth() == 11 && date.getDate() == 25) {
	displayMessage("It's Christmas. And you've viewed this widget over ten thousand " +
	       "times. Maybe you should go build a snowman.");
}

AS3

var upv:String = _api.context.user.PLACEMENT_VIEWS;
var date:Date = new Date();
if (upv > 10000 && date.getMonth() == 11 && date.getDate() == 25) {
	displayMessage("It's Christmas. And you've viewed this widget over ten thousand " +
	       "times. Maybe you should go build a snowman.");
}

JavaScript

var upv:String = _api.context.user.PLACEMENT_VIEWS;
var date:Date = new Date();
if (upv > 10000 && date.getMonth() == 11 && date.getDate() == 25) {
	displayMessage("It's Christmas. And you've viewed this widget over ten thousand " +
	       "times. Maybe you should go build a snowman.");
}
back to table

context.user.geo.getCountry

method

Returns the user's ISO-3166 country code (e.g., "US"). See the ISO-3166 decoding table

Parameters
None
Return
String: Country code.
Example Usage

AS2

switch (_level0.cs.context.user.geo.getCountry())
{
	case "US" :
		showColorPicker();
		break;
	default :
		showColourPicker():
}

AS3

switch (_api.context.user.geo.getCountry())
{
	case "US" :
		showColorPicker();
		break;
	default :
		showColourPicker():
}

JavaScript

// Note: Not available in JS container

switch (_api.context.user.geo.getCountry())
{
	case "US" :
		showColorPicker();
		break;
	default :
		showColourPicker():
}
back to table

context.user.geo.getContinent

method

Returns the user's continent code: AF (Africa), AS (Asia), EU (Europe), NA (North America), OC (Oceania), SA (South America), or OT (others; i.e., Antarctica).

Parameters
None
Return
String: Continent code.
Example Usage

AS2

if (_level0.cs.context.user.geo.getContinent() == "OT") {
	displayMessage("Um, where are you?");
}

AS3

if (_api.context.user.geo.getContinent() == "OT") {
	displayMessage("Um, where are you?");
}

JavaScript

// Note: Not available in JS container

if (_api.context.user.geo.getContinent() == "OT") {
	displayMessage("Um, where are you?");
}
back to table

context.user.geo.getRegion

method

Returns ISO-3166 state/province codes; available for these countries only: US, CA, AU, GB, JP, BR, DE, and CN.

Parameters
None
Return
String: State/province code for supported countries.
Example Usage

AS2

switch (_level0.cs.context.user.geo.getCountry())
{	
	case "AU":
	case "BR":
	case "CA":
	case "CN":
	case "DE":
	case "GB":
	case "JP":
	case "US":
		setRegionDefault(_level0.cs.context.user.geo.getRegion());

		break;
	default:
		// no default available
}

AS3

switch (_api.context.user.geo.getCountry())
{	
	case "AU":
	case "BR":
	case "CA":
	case "CN":
	case "DE":
	case "GB":
	case "JP":
	case "US":
		setRegionDefault(_api.context.user.geo.getRegion());

		break;
	default:
		// no default available
}

JavaScript

// Note: Not available in JS container

switch (_api.context.user.geo.getCountry())
{	
	case "AU":
	case "BR":
	case "CA":
	case "CN":
	case "DE":
	case "GB":
	case "JP":
	case "US":
		setRegionDefault(_api.context.user.geo.getRegion());

		break;
	default:
		// no default available
}
back to table

context.user.geo.getZIP

method

Returns five-digit ZIP code, if the user is in America.

Parameters
None
Return
String: ZIP code
back to table

context.user.geo.getLatLon

method

Returns the user's estimated latitude and longitude. For convenience, we package latitude and longitude into a single object tuple.

Parameters
None
Return
Object: {lat: [float], lon: [float]}.
Example Usage

AS2

var latlon:Object = (_level0.cs.context.user.geo.getLatLon());
if (latlon.lat > 60 || latlon.lat < -60)
{
	sellSpaceHeaters();
}
else 
{
	sellRefrigerators();
}

AS3

var latlon:Object = (_api.context.user.geo.getLatLon());
if (latlon.lat > 60 || latlon.lat < -60)
{
	sellSpaceHeaters();
}
else 
{
	sellRefrigerators();
}

JavaScript

var latlon = (_api.context.user.geo.getLatLon());
if (latlon.lat > 60 || latlon.lat < -60)
{
	sellSpaceHeaters();
}
else 
{
	sellRefrigerators();
}
back to table

context.user.geo.getNetwork

method

Returns a single character representing user's Internet connection: M (modem), I (ISDN), C (cable) or D (DSL).

Parameters
None
Return
String: Internet connection code.
Example Usage

AS2

if (_level0.cs.user.geo.getNetwork() != "M")
{
	showCoolContent();
}
else
{
	commiserate();
}

AS3

if (_api.user.geo.getNetwork() != "M")
{
	showCoolContent();
}
else
{
	commiserate();
}

JavaScript

// Note: Not available in JS container

if (_api.user.geo.getNetwork() != "M")
{
	showCoolContent();
}
else
{
	commiserate();
}
back to table


Getting Context in Server-Side Code

Sometimes it is useful to receive context information on a requested widget when it is loaded from your server, not just once inside the widget. We support passing URL arguments to your widget source URL, in addition to the services being available in-widget through our APIs. You can use this information to control what is actualy served, if you so choose.

To maintain performance, we avoid sending all available context information to your server by default. You need to tell the platform which parameters you'd like to receive, and you can do so through the Widget Console with the Edit Widget -> Context Parameters tool.

Name Querystring Parameter Description
User geolocation _cs_geo Where is the visitor? Includes continent, country, region, latitude, longitude, ZIP code (see below)
User network _cs_net What kind of network does the visitor have--DSL, cable, dialup, or ISDN? Also includes throughput (see below)
Placement domain _cs_dom Domain of current placement, when available
Placement URL _cs_pur URL of current placement, when available
Placement children _cs_ptc Number of child instances created by this placement
Widget children _cs_wtc Number of total placements for this widget
User widget views _cs_wtv Minimum number of widget views by this visitor, counting this one
User placement views _cs_ptv Minimum number of placement views by this visitor, counting this one

Parsing Geolocation

The geolocation string uses a special format save space--instead of injecting ZIP code, country, etc. separately, we compress them as a single parameter. Within your widget, you can use our helpful getters. In your server-side application, you can parse the geolocation string using the following JavaScript-esque pseudo-code:

/// @returns ISO-3166 country code (e.g., "US")
function getCountry(geo)
{
   return geo.substr(7, 2);  
}

/// @returns two-digit continent code: AF (Africa), AS (Asia), EU (Europe), 
/// NA (North America), OC (Oceania), SA (South America),
/// or OT (others) if you have visitors from Antarctica
function getContinent(geo)
{
   return geo.substr(5, 2);  
}

/// @returns ISO-3166 state/province codes. 
/// Available for these countries: US, CA, AU, GB, JP, BR, DE, CN.
function getRegion(geo)
{
   return geo.substr(9, 2);
}

/// @returns ZIP code (only available in US)
function getZIP(geo)
{
  return geo.substr(0, 5); 
}

/// @returns floating point latitude
function getLatitude(geo)
{
  return convertLocation(geo.substr(11, 4)); 
}

/// @returns floating point longitude
function getLongitude(geo)
{
  return convertLocation(geo.substr(15, 4)); 
}

// Encoding for latitude and longitude is 3.1 FP ASCII encoding.
// Say the server sees the user is at 33.9931 degrees. It uses the following algorithm:
// 1. Add 180 to get 213.9931. 
// 2. Truncates after one decimal place of precision, to create 213.9. 
// 3. Remove the decimal point, returning the string "2139"

function convertLocation(latlon)
{
  return parseInt(latlon, 10) / 10 - 180;
}

Parsing Network Descriptor

The network string, like the geolocation string, also requires special parsing functions.

function getNetwork(cs)
{
   return cs.substr(0, 1); // returns M (modem), I (isdn), C (cable) or D (dsl)
}

function getThroughput(cs)
{
   return cs.substr(1, 1); // returns V (very high), H (high), M (medium), L (low)
}