W3C

The Widget Interface

W3C Working Draft 7 September 2010

This Version:
http://www.w3.org/TR/2010/WD-widgets-apis-20100907/
Latest Version:
http://www.w3.org/TR/widgets-apis/
Previous Versions:
http://www.w3.org/TR/2009/CR-widgets-apis-20091222/
http://www.w3.org/TR/2009/WD-widgets-apis-20091117/
http://www.w3.org/TR/2009/WD-widgets-apis-20090818/
http://www.w3.org/TR/2009/WD-widgets-apis-20090423/
http://www.w3.org/TR/2009/WD-widgets-apis-20090205/
Editors:
Marcos Cáceres, Opera Software ASA
Robin Berjon, Vodafone
Arve Bersvendsen, Opera Software ASA

Abstract

This specification defines an application programming interface (API) for widgets that provides, amongst other things, functionality for accessing a widget's metadata and persistently storing data.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is the 7 September 2010 Last Call Working Draft version of "The widget Interface" specification. The Last Call period ends on 28 September 2010. The purpose of this Last Call is to inform the community of the removal of a feature from the specification (the openURL() method, see changes since last publication). Please submit comments to the Working Group's public mailing list (public archive).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is produced by the Web Applications WG, part of the Rich Web Clients Activity in the W3C Interaction Domain. It is expected that this document will progress along the W3C's Recommendation track. Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

Table of Contents

1. Introduction

This section is non-normative.

This specification defines an application programming interface that enables baseline functionality for widgets, including the ability to:

This specification uses [WebIDL] to specify application programming interfaces.

1.1. The Widget Family of Specifications

This section is non-normative.

This specification is part of the Widgets Family of specifications, which together standardize widgets as a whole. The list of specifications that make up the Widgets Family of Specifications can be found on the Working Group's wiki.

1.2. Design Goals and Requirements

This section is non-normative.

The design goals and requirements for this specification are documented in the Widgets Requirements [Widgets-Reqs] document.

This document addresses some of the requirements relating to Application Programming Interfaces of the 30 April 2009 Working Draft of the Widgets: Requirements Document:

1.3. Changes Since Last Publication

This version of the specification drops support for the openURL method, which was part of previous versions of this specification. The Working Group found a number of privacy and security issues relating to openURL, as well as a way to achieve the same intended functionality via other means, and hence decided to drop it from the specification.

The working group recommends that authors use HTML's a element to achieve the same functionality, or use the window.open() method where appropriate. Some examples of how the a element can be used to achieve the same functilaity as openURL are given below. Of course, the examples will only work on implementations that actually have scheme handlers to handle each type of URI.

Send email:
Was: openURL("mailto:jsmith@example.org?subject=A%20Hello&body=hi")
Now: <a href="mailto:jsmith@example.org?subject=A%20Hello&amp;body=hi">Email Jane</a>
Make a phone call:
Was: openURL("tel:+1234567678")
Now: <a href=""tel:+1234567678">Call Bill!</a>
Open a web page:
Was: openURL("http://example.org")
Now: <a href="http://example.org">Example</a>
Send and sms:
Was: openURL("sms:+41796431851,+4116321035;?body=hello%20there")
Now: <a href="sms:+41796431851,+4116321035;?body=hello%20there">SMS Bob</a>

2. Conformance

All examples and notes in this specification are non-normative, as are all sections explicitly marked as non-normative. Everything else in this specification is normative.

The key words must, must not, should, recommended, may and optional in the normative parts of this specification are to be interpreted as described in [RFC2119].

Only user agents can claim conformance to this specification. Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent to what would be achieved when following the specification.

Note: Implementers can partially check their level of conformance to this specification by successfully passing the test cases of the [Interface-Test-Suite]. Passing all the tests in the test suite does not imply conformance to this specification; It only implies that the implementation conforms to aspects tested by the test suite.

3. Definitions

The following definitions are used throughout this specification. Please note that the following list is not exhaustive; other terms are defined throughout this specification.

Author script

Some code running within a widget instance (e.g., some ECMAScript).

Configuration document

A configuration document is reserved file called "config.xml" at the root of the widget package as specified in the [Widgets-Packaging] specification.

Feature

A runtime component (e.g. a device API, video decoder, etc.) that is made available by the user agent to the widget instance as a direct result of an author requesting its availability via a feature element in the widget's configuration document.

Getting

A DOM attribute is said to be getting when its value is being retrieved (e.g. by an author script).

Initialization

The act of user agent processing a widget package through the Steps for Processing a Widget Package, as specified in the [Widgets-Packaging] specification.

Preference

A persistently stored name-value pair that is associated with the widget the first time the widget is initiated.

Start file

A file in the widget package to be loaded by the user agent when it instantiates the widget, as specified in the [Widgets-Packaging] specification.

Supports

A user agent implements a mentioned specification or conformance clause.

Valid IRI

A string that matches the IRI token of the [IRI] specification.

Viewport

A CSS viewport. For a start file rendered on continuous media, as defined in the [CSS] specification, a viewport is the area on which the Document of the start file is rendered by the user agent. The dimensions of a viewport excludes scrollbars, toolbars, and other user interface "chrome".

Widget Instance

A browsing context that comes into existence after initialization. The concept of a browsing context is defined in [HTML5]. Multiple widget instances can be instantiated from a single widget package. A widget instance is unique and does not share any DOM attribute values or storage areas with any other widget instance.

4. User Agents

A user agent is a software implementation of this specification that also supports the [Widgets-Packaging] specification.

Note: The user agent described in this specification does not denote a "widget user agent" at large. That is, a user agent that implements all the specifications, and dependencies, defined in the Widgets: Family of Specifications. The user agent described in this specification is only concerned with the behavior of programming interfaces. A user agent needs to impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.

5. The Widget Interface

An object that implements the Widget interface provide the following attributes and method:


[NoInterfaceObject]
interface Widget {
    readonly attribute DOMString     author;
    readonly attribute DOMString     authorEmail;
    readonly attribute DOMString     authorHref;
    readonly attribute DOMString     description;
    readonly attribute DOMString     id;
    readonly attribute DOMString     name;
    readonly attribute DOMString     shortName;
    readonly attribute Storage       preferences;
    readonly attribute DOMString     version;
    readonly attribute unsigned long height;
    readonly attribute unsigned long width;
};

Note: A user agent can support the Storage interface on DOM attributes other than the preferences attribute (e.g., a user agent can support the [WebStorage] specification's localStorage attribute of the window object in conjunction to the preferences attribute). For the sake of interoperability across widget user agents, and where it makes sense, authors can use the preferences attribute in conjunction to other APIs that provide a Storage interface.

For a widget instance, a user agent must expose a unique object that implements the widget interface to author scripts. User agent implementing [HTML5]'s Window interface must implement the Widget interface as the widget attribute of the window object in the manner defined by the WindowWidget interface.


[Supplemental, NoInterfaceObject]
interface WindowWidget {
  readonly attribute Widget widget;
};

Window implements WindowWidget;

When an object implementing the Widget interface is instantiated, if a user agent has not previously associated a storage area with the instance of a widget, then the user agent must initialize the preferences attribute.

If a user agent has previously associated a storage area with a widget instance, the user agent must not re-initialize the preferences attribute unless explicitly requested to do so by the end-user or for security reasons. Instead, the previously associated storage area (or an equivalent clone) can be accessed using the Storage interface.

5.1. Metadata Attribute Values

Most of the attributes of the widget interface correspond to the metadata derived from the initialization process.

When an object implementing the Widget interface is instantiated, a user agent sets the attributes identified in the left column of the configuration attributes table to the values that correspond to values in table of configuration defaults as defined in [Widgets-Packaging] (identified by the values in the right hand column).

Upon getting any of the attributes from the attributes column of the configuration attributes table, a user agent must return the corresponding value from the 'Values in Table of Configuration Defaults' column.

Configuration Attributes Table
Attributes Values in Table of Configuration Defaults
author author name
authorEmail author email
authorHref author href
description widget description
id widget id
name widget name
version widget version
shortName widget short name

5.1.1. Usage Example

This section is non-normative.

<!doctype html>
<title>Hypothetical example that emails an Author</title>
<a style="display:hidden">Email bug</a>
<script>
function emaulAuthor(msg){
    var a        = document.getElementsByTagName("a")[0]; 
    var subject  = widget.name   + " (" + widget.version + ")";
    var to       = widget.authorEmail;
    var emailURI =    "mailto:"   + to 
                    + "?subject=" + escape(subject) 
                    + "&body="    + escape(msg);  
	  a.setAttribute("href", emailURI);
    a.click();      
}  

// Hypothetical example that generates an about box 
// using metadata from a widget's configuration document. 
function makeAboutBox(){
    var title    = "<h1>" + widget.shortName + "</h1>";
    var version  = "<h2>Version: " + widget.version + "</h2>";
    var id       = "<p><small>" + widget.id +"</small></p> <hr/>";
    var auth     = "<p>Created by: " + widget.author + "</p>"; 
    var homepage = "<p>My Site: "  +widget.authorHref + "</p>" 
    var desc     = "<h3>About this Widget</h3><p>"  
                  + widget.description + "</p>"
    var button  = "<button onclick='emailBug("hello there!")'>Email Bug</button>";
    var box      = "<div id='aboutBox'>"   
                   + title + version + id + auth + desc +
    "</div>";

    document.getElementById("console").innerHTML = box; 
}
makeAboutBox();
</script>

5.2. The width Attribute

Upon getting the width attribute, a user agent must return an number that represents the width of the widget instance’s viewport in [CSS] pixels.

5.3. The height Attribute

Upon getting the height attribute, a user agent must return a number that represents the height of the widget instance’s viewport in [CSS] pixels.

5.4. The preferences Attribute

The preferences allows authors to manipulate a storage area that is unique for the instance of a widget. It does this by implementing the Storage interface specified in [WebStorage].

Upon invocation of the setItem() or removeItem() method by an author script on an item that is not a read-only item, a user agent must queue a task to fire an event with the name storage, which does not bubble and is not cancelable, and which uses the StorageEvent interface, at each Window object whose widget object has a Storage object that is affected. The concept of queue a task is defined in [HTML5]. Storage event and the StorageEvent interface is defined in [Storage].

Upon invocation of the setItem() or removeItem() method by an author script on a read-only item, a user agent must throw a NO_MODIFICATION_ALLOWED_ERR exception and must not fire a storage event. The NO_MODIFICATION_ALLOWED_ERR is defined in the [DOM3Core] specification.

Upon invocation of the preferences attribute's clear() method, a user agent must not remove read-only items and corresponding values from a storage area. A user agent must, however, remove other items from the storage area in the manner described in the [WebStorage] specification without throwing a NO_MODIFICATION_ALLOWED_ERR exception for items that the user agent cannot remove.

When getting the preferences attribute, if the origin of a widget instance is mutable (e.g., if the user agent allows document.domain to be dynamically changed), then the user agent must perform the preference-origin security check. The concept of origin is defined in [HTML5].

5.4.1. Preference Origin Security Check

The steps to perform the preference-origin security check are given by the following algorithm:

  1. If the Document's effective script origin is not the same origin as the Document's origin, then throw a SECURITY_ERR exception and abort these steps. The concept of effective script origin and same origin are defined in [HTML5].

  2. Return the Storage object associated with that widget instance's preferences attribute.

5.4.2. Initialization of the preferences Attribute

The steps to initialize the preferences attribute are given by the following algorithm:

  1. Establish the instance of a widget for this widget and create a storage area that is unique for the origin unique and for that instance.

  2. If the widget preferences variable of the table of configuration defaults contains any preferences, then for each preference held by widget preferences:

    1. Let pref-key be the name of the preference.

    2. If the pref-key already exists in the storage area, stop processing this preference: go back to step 2 in this algorithm, and process the next preference (if any).

    3. Let pref-value be the value of the preference.

    4. Directly write pref-key and pref-value to the storage area (i.e., don't use the Storage interface to avoid firing storage events):

      1. If the user agent cannot write to the storage area (e.g., because it ran out of disk space, or the space quota was exceeded, etc.), terminate all processing of this widget. It is recommended that the user agent inform the end-user of the error.

      2. If this preference's associated readonly value is true, then flag this key as a read-only item in the storage area.

  3. Implement the Storage interface on the storage area, and make the preferences attribute a pointer to that storage area.

5.4.3. Usage Example: Getting and Setting Preferences

This section is non-normative.

The following example shows the different means by which an author can interface with the preferences attribute in ECMAScript. The possibilities include using either the getItem and setItem methods, or bracket access (or a combination of both).



<!doctype html>

...

<fieldset id="prefs-form">
<legend>Game Options</legend>
  <label>Volume:  <input type="range" min="0" max="100" name="volume"/> </label> 
  <label>Difficulty:  <input type="range" min="0" max="100" name="difficulty"/> </label>
  <input type="button" value="Save" onclick="savePrefs()"/>
  <input type="button" value="load" onclick="loadPrefs()"/>
</fieldset>

...

<script>
var form   = document.getElementById("prefs-form");
var fields = form.querySelectorAll("input[type='range']"); 
function loadPrefs () {
   for(var i = 0; i < fields.length; i++){
      var field = fields[i];
      if (typeof widget.preferences[field.name] !== "undefined") {
        field.value = widget.preferences.getItem(field.name); 
      }
   }  
}

function savePrefs () {
  for(var i = 0; i < fields.length; i++){
      var field = fields[i];
      widget.preferences.setItem(field.name,field.value);
  }
}
</script>

5.4.4. Usage Example: Interacting with the Preferences declared in a Configuration Document

This example demonstrates the expected behavior of a user agent that is interacting with preferences that were declared in a configuration document. The user is able to modify and save various preferences. However, if the user attempts to modify and save the license key, which is set to read-only, the widget will throw an error and display an alert message.

<!-- Configuration Document -->

<widget xmlns="http://www.w3.org/ns/widgets"> 
  <name>The 80's: Greatest Hits!</name>
  <preference name="licenseKey" 
              value="f199bb20-1499-11df" 
              readonly="true"/>
  <preference name="favtrack" 
              value="billy"/>

  <preference name="playorder"
              value="1" />  
</widget>



<!doctype html>

...

<script>
var fields;
function init(){
  fields = document.forms[0].elements;
  loadPrefs()
}


function loadPrefs () { 
  for(var i = 0; i < fields.length; i++){
     var field = fields[i]; 
     if (typeof widget.preferences[field.name] !== "undefined") {
        field.value = widget.preferences[field.name]; 
     }
  } 
}

function savePrefs () {
  for(var i = 0; i < fields.length; i++){
    var field = fields[i];
    try{
      widget.preferences.setItem(field.name,field.value);
    }catch(e){
       if(e.code === DOMException.NO_MODIFICATION_ALLOWED_ERR){
          alert(e);
       }
    }
   }
  }
</script>

<body onload="init()">
  <fieldset id="prefs-form">
  <legend>Album Playback Settings</legend>
  <form>
  <label>Volume: 
  <input type="range" min="0" max="100" step="10.0" value="50" name="volume"/> 
  </label>
  <label>Playback: 
  <select name="playorder"> 
     <option value=0>Loop
     <option value=1>Random 
     <option value=2>Normal
  </select>
  </label>

  <label>Favorite Song

  <select name="favtrack">
     <option value=kate>Kate Bush: Babooshka
     <option value=billy>Billy Idol: White Wedding 
     <option value=culture>Culture Club: Karma Chameleon
  </select>
  </label> 

  <label>License Key: <input name="licenseKey"></label> 
</form> 
<button onclick="savePrefs()">Save</button>
<button onclick="loadPrefs()">Load</button>
</fieldset>

...

6. Storage Areas

A storage area is a data-store that is unique for the widget instance, which a user agent uses to store key-value pairs that pertain to the preferences attribute. An author script interacts with the storage area via the [WebStorage] specification's Storage interface. To facilitate the storage of preferences during the initialization of the preferences attribute, a user agent needs to have the ability to directly read and write to a storage area without invoking the methods of the [WebStorage] specification's Storage interface.

A user agent must preserve the values stored in a storage area when a widget is re-instantiated (i.e., when the device is rebooted and the widget is reopened, the previously set data is made available to the storage area).

A user agent may expire data from a storage area for security reasons, or when requested to do so by the end user, or if the user agent detects that it has limited storage space.

6.1. Read-only Items

As an extension to the [WebStorage] specification, this specification allows certain key-value pairs (items) in a storage area to be read-only: a read-only item is an item in a storage area that cannot be modified or deleted by an author script. A read-only item always represents a preference that author explicitly flagged as "read-only" in the widget's configuration document (denoted by a preference element having a readonly attribute value set to true).

Acknowledgements

Max Froumentin, Rune F. Halvorsen, Addison Phillips, Alexander Dreiling, Arun Ranganathan, Arthur Barstow, Bárbara Barbosa Neves, Brian Wilson, Bjoern Hoehrmann, Benoit Suzanne, Bert Bos, Boris Zbarsky, Bradford Lassey, Cameron McCormack, Cliff Schmidt, Claudio Venezia, Coach Wei, Corin Edwards, Cyril Concolato, Dan Brickley, David Clarke, Dean Jackson, David Pollington, Doug Schepers, Ed Voas, Felix Sasaki, Francois Daoust, Gautam Chandna, Geir Pedersen, Gene Vayngrib, Gorm Haug Eriksen, Guido Grassel, Hari Kumar G, Ian Hickson, Jay Sweeney, Jere Käpyaho, Jim Ley, Jon Ferraiolo, Jose Manuel Cantera Fonseca, Josh Soref, Jouni Hakala, Joey Bacalhau, Kevin Lawver, Kai Hendry, Krzysztof Maczy?ski, Lachlan Hunt, Marc Silbey, Marcin Hanclik, Mark Baker, Mikko Pohja, Mohamed Zergaoui, Olli Immonen, Philipp Heltewig, Philip Taylor, Scott Wilson, Stephen Paul Weber.

Normative References

[CSS]
Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification, B. Bos, I. Hickson, T. Çelik, H. Wium Lie. W3C Candidate Recommendation 23 April 2009.
[DOM3Core]
Document Object Model (DOM) Level 3 Core Specification, A. Le Hors, P. Le Hégaret, L. Wood, G. Nicol, J. Robie, M. Champion, S. Byrne, editors.W3C Recommendation 07 April 2004.
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels, RFC2119, S. Bradner. March 1997.
[IRI]
Internationalized Resource Identifiers (IRIs). RFC3987, M. Duerst, M. Suignard. January 2005.
[Widgets-Packaging]
Widget Packaging and Configuration. M. Cáceres. W3C Candidate Recommendation 01 December 2009.
[WebIDL]
Web IDL. Cameron McCormack. W3C Working Draft, 19 December 2008. (Work in progress).
[WebStorage]
Web Storage. I. Hickson. W3C Working Draft, 22 December 2009. (Work in progress).
[HTML5]
HTML5. I. Hickson. W3C Working Draft, 25 August 2009. (Work in progress).

Informative References

[Interface-Test-Suite]
Test Suite for the Widget Interface Specification. Marcos Cáceres and Dominique Hazaël-Massieux. Work in Progress.
[Widgets-Reqs]
Widgets Requirements. M. Cáceres and M. Priestley. W3C Working Draft, 30 April 2009 (Work in progress).