Web Technologies for Opera Web Applications

By Hans S. Tømmerholt

14th December 2011: This article is obsolete

This article is obsolete/out of date, so should no longer be treated as a current or reliable source of information. Please consult the following for more up-to-date information:

The basis of a Web application is usually HTML. The HTML documents are translated into a DOM data structure by the browser. The DOM tree can be modified through scripting, often in ECMA/JavaScript, where elements can be added, changed, or removed through DOM bindings in the scripting environment. The result is a document that can change dynamically. Combine this with networking capability through the XMLHttpRequest object, and you have a fully working Web application. Opera also has support for various multimedia such as SVG, Canvas and the Audio object.

  1. HTML - HyperText Markup Language
  2. XML - Extensible Markup Language
  3. DOM - Document Object Model
  4. ECMA/JavaScript
  5. CSS - Cascading Style Sheets
  6. XSLT - Extensible Style sheet Language: Transform
  7. Networking
    1. The XMLHttpRequest object
    2. DOM Level 3: Load and Save
    3. Script tag hack
    4. The Iframe hack
  8. Web Forms
  9. Cross document messaging
  10. Multimedia
    1. SVG - Scalable Vector Graphics
    2. Canvas
    3. The Audio object
  11. References

HTML - HyperText Markup Language

HTML is the oldest and most widespread language on the Web. It describes hyperlinked documents where the content is marked up with tags, or elements, that identify semantic parts of the document, such as paragraphs, headings, and lists.

<!DOCTYPE html>
<html>
  <head>
    <title>A Web page</title>
  </head>
  <body>
    <h1>A Web page</h1>
    <p>A <a href="foo.html">link</a>.</p>
  </body>
</html>

HTML has several types of elements divided into two categories, block elements and inline elements. Block elements separate the document into different types of sections. Examples include the p (paragraph), ul (unordered list) and table (tabular data) elements. Inline elements refer to parts of a sentence, for example surrounding a set of words. Examples include the q (quote), code (program code) and dfn (definition) elements. Through the use of these different elements, content can be marked up to identify the different kinds of content in the document. The different elements can have attributes, name-value pairs which further qualify the elements with information. Examples include the id (identifier), href (hypertext reference, a link URL), and lang (language) attributes.

HTML comes in two flavours: HTML and XHTML. The latter is an application of XML, meaning that it is required to be well formed, but thus also easier to parse. The content of the languages is mostly the same, meaning the same elements and attributes are available. However, there are slight differences in how Opera handles the two. See the document on doctypes in Opera [OPERADOCTYPE] for more information.

See the HTML specification [HTML4] and the XHTML specification [XHTML] for more information.

XML - Extensible Markup Language

XML is not a language as such, but rather a meta-language used to describe languages for representing data. It serves as the basis for applications like SVG and XHTML. The syntax defines elements, which may have attributes and contain text and other elements.

<foo bar="foo">
  <bar>Foobar!</bar>
</foo>

This example shows a simple, but correct XML document. The author decides which names are used for the elements and attributes. Usually the grammar, the legal list of elements and attributes for an application, is formalized in a Document Type Definition (DTD) or XML Schema. There are also other standards for formalizing XML grammars like RelaxNG.

An XML document must be well formed, meaning in particular:

  • All elements must be closed, either having a closing tag (<foo>..</foo>), or be closed "in themselves" (<foo/>).
  • Elements must be nested correctly. This means that an element's end tag must follow all other end tags of elements opened inside the element: <foo><bar>..</foo></bar> is illegal.
  • Attributes must be enclosed in quotes, either " or '.

Unless a style sheet is attached, arbitrary XML will be displayed as a block of text (the default display in CSS). The example above will result simply in a page saying "Foobar!".

See the XML specification [XML] for more information.

DOM - Document Object Model

The DOM is an interface which exposes the structure of a document to programming languages. With the help of the DOM, developers can add, remove, hide, and change elements, or nodes (elements, attributes, text, comments, and more), in a document dynamically and programmatically. One can also retrieve nodes from the existing document and inspect them. The DOM defines an API, which guarantees that the way to program is the same across programming languages, be it JavaScript, Perl or Java. The following example uses JavaScript:

//Create a new node
var bar = document.createElement( "bar" );
//Give it an attribute		
bar.setAttribute("foo", "foobar");		
//Retrieve existing node
var foo = document.getElementsByTagName('foo')[0];	
//Add new node to existing parent
foo.appendChild(bar);					

The DOM is a basis for language-specific extensions. The two most prominent are the HTML and Style DOMs. For each type of element in HTML, there is a corresponding class. The select element has a class called HTMLSelectElement. The HTML DOM offers HTML specific objects and shortcuts like the document.body property and properties and methods like selectedIndex and add(option) on HTMLSelectElement objects.

The DOM specifications come in different versions called levels, and the latest release is level 3. Level 0 is not a specification but refers to the pre-standard implementations by Netscape and Internet Explorer.

See the following links for more information:

ECMA/JavaScript

JavaScript is a scripting language, a simple programming language which runs in the browser. The syntax is similar to Java and C, although the language behavior is different. Since its original inception by Netscape in 1995, the language has evolved to incorporate a large set of features. The language is standardized by the Ecma standards organization, under the name of ECMAScript, or ECMA-262 as it is the 262nd standard created by the organization. ECMAScript is currently in the 3rd edition (version), with the 4th edition under development. Like other programming languages, JavaScript offers variables, functions, data types, string processing, regular expressions and the like. It can also offer an interface to functionality in the browser, such as opening windows, manipulating the browser's history and current location.

An HTML or XML document may contain JavaScript code or refer to external scripting files through the script element.

<script type="text/javascript">
  function foo() {
    alert('foo');
  }
</script>

In the example above, an alert box is shown when the function foo is executed.

The language is the host to the DOM bindings in the browser, and contains a reference to the current document. The document property from the DOM example above is an example of a property which is inserted into the scripting environment. Through this property, programmers can access the contents of the current document through the DOM API.

JavaScript communicates with the users through events. When a user clicks a button or enters text into an HTML form, an event is fired and received by the scripting environment. The author may create event listeners written in JavaScript which react to the event by for example getting some data from a server and inserting the data into the document.

<input type="button" onclick="foo()" value="Click me!">

In the example above, the function foo from the previous example is called when the user clicks the button.

For more maintainable code event listeners can be kept in the script itself, thus allowing changes in the document without having to rewrite the event handler attributes (like onclick in the example above).

See the following links for more information:

  • The ECMAScript 262 specification [ECMASCRIPT].
  • JavaScript tutorial at HowToCreate.co.uk [HOWTOJS].
  • Efficient JavaScript at dev.opera.com [EFFJS].
  • JavaScript resources at crockford.com [CROCKFORD].

CSS - Cascading Style Sheets

Where HTML is used to mark up a text in a semantic manner, CSS is used to determine how that text is to be presented. Fonts, colors, backgrounds, and layout are all governed by CSS. The language consists of selectors and style rules. A selector defines which elements of a page are to be affected by a set of style rules. Examples include p, meaning any p element, .foo, meaning any element with the foo class or foo bar, meaning any element of type bar, which is a descendant of any element of type foo. Style rules are name/value pairs, where the names are CSS properties such as color, background, position and so on.

p.big {
  font-size: 14pt;
  color: darkgrey;
}

The example states that all text inside p elements with a class attribute with the value big, should have a 14 pt font size and be dark grey.

Style rules are connected to a document either through an element's style attribute, the style element in the document's head element, or through references to external stylesheets through a link element.

The current version of CSS is 2.1, although CSS3 is under development. Opera already has experimental support for parts of the CSS3 specification.

See the following links for more information:

XSLT - Extensible Stylesheet Language: Transform

XSLT is used to transform an XML document to a new XML structure, into HTML or plain text. Transformation is done through matching different fragments of a document with templates, extracting data from the old XML structure, and inserting it into a new one. A use case is storing all data in one internal XML format, using transformations to produce different views or formatting of the data.

Example:

This XML document...

<foo>
  <bar>foo</bar>
</foo>

...transformed with this XSLT...

<xsl:stylesheet>
  <xsl:template match="foo">
    <foobar><xsl:value-of select="bar"/></foobar>
  </xsl:template>
</xsl:stylesheet>

...will produce the following XML document:

<foobar>foo</foobar>

See the XSLT specification [XSLT] for more information.

Networking

Opera supports several technologies for retrieving data over the Web. The most common in use today is the XMLHttpRequest object. Before this, one would typically use iframes or import external scripts to get data into the application. These methods have their uses, but XMLHttpRequest is by far the most useful.

The XMLHttpRequest object

Opera supports the XMLHttpRequest JavaScript object (XHR). With this object, the developer can make requests for small amounts of data from a server. Results are normally returned as XML which becomes interpreted into a complete DOM tree. The response is available in the responseText and responseXML of the object.

The basic functionality of the XHR object is that you create one, bind a event handler to the object, open a URL and send data, for example POST data. When a response is received, the event handler is triggered. This is demonstrated in a simple example:

var req = new  XMLHttpRequest ();
req.onreadystatechange = function () {
  if ( req.readyState == 4 ) {		
     //The request is completed
    if ( req.status == 200 ) {		
        //The HTTP status code is ok
      opera.postError(req.responseXML.documentElement.nodeName);
      opera.postError(req.responseText)
    } else {
      //handle errors
    }
  }
}
req.open( 'GET', 'http://example.com/file.xml', true );
req.send(null);

In the example, the XML data from file.xml get translated into a DOM tree and stored in the req.responseXML variable. req.responseText contains the actual XML text.

XHRs can be done in synchronous and asynchronous fashion, using the third argument to the open method. In most cases you'll want the latter. In synchronous mode, the request will halt the executing script until the request is completed and a response is received.

If the data received from an XHR is not XML or fails parsing as such, responseXML contains an empty DOM tree, not null. req.responseText contains the data received.

XHR relies on a same-origin policy which states that an XHR sent from a document may only get a response from the same server that served the document. Other attempts consitute a security violation and will fail. This security feature is disabled in widgets in order to make them more useful.

Keep in mind that running several XHRs at the same time, may cause each of them to run slowly. Note also that the connection phase may take some time on low end devices, in which case some sort of progress bar should be displayed to the user.

See the W3C working draft on XMLHttpRequest [XHR].

DOM Level 3: Load and Save

W3C supplies its own methods in their DOM Level 3: Load and Save recommendation. Here one creates a specific LSParser object, which then parses an URI. LSParser objects can parse in a synchronous or asynchronous mode, and may also parse strings.

var di = document.implementation;
var parser document.implementation.createLSParser( di.MODE_ASYNCHRONOUS );
parser.onload = function (evt) {
  alert(evt.newDocument.documentElement);
}
parser.parseURI('http://example.com/doc.xml');

In this example, the LSParser is used in asynchronous mode. In this case, a load event is fired when the document is fully loaded. The parseURI method itself returns null, and the new document must be picked up in an onload event handler.

DOM Level 3: Load and Save is supported by Opera, but is not in widespread use.

See the DOM Level 3: Load and Save specification [DOM3LS].

Script tag hack

It is possible to add references to external scripts through the DOM. The script will then be downloaded and executed by the browser. Variables and functions in the script will be inserted into the global scope. Beware of this approach, as it may load potentially harmful code if the source is not trustworthy.

var newScript = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/example.js';
document.body.appendChild(script);
document.body.removeChild(script); 
//Clean up

The iframe hack

A document may contain several iframes, which may again connect to any webpage. However, it is only possible to access a document in an iframe via the DOM if that document is loaded from the same origin as the owner document. So, this works just like XMLHttpRequest. Data can be retrieved and accessed from the same origin. The iframe may be used to load an XML file, as in the following example:

var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'the guidelines.html';
iframe.onload = function () {
  processData(this.contentDocument);
  document.body.removeChild(this);
};
document.body.appendChild(iframe);
opera.postError('added');

Web Forms

Opera has experimental support for Web Forms on all platforms. The Web Forms specification defines some extensions to the HTML Form model, including for example more input types like email, number and url, form control repetition, client-side validation and more.

An example using the range type:

<input type="range" min="0" max="10" step="2" required="required">

Opera will render this as a slider with a wide space between six markers.

%5BSlider%5D

Opera now also supplies its own graphical widget for date and time:

<input type="datetime" name="birthdate">

%5BDatetime%5D

The Web Forms specification allows repeating form controls. This enables Web authors to define a template set of form controls, which may then be repeated a chosen number of times in the page. In addition, there is support for automated adding and removal of these repetitions, using type="add" and type="remove" attribute on buttons.

In the following example the li element, containing one text input and one remove button is repeated three times. The text field in each repetition is assigned a running id, 0, 1, etc, which allows all the inputs to be submited in the same form. In this case, the id ([foo]) is enclosed in yet another set of brackets, to denote the array syntax supported by for example PHP.

<form action="script.cgi" method="get">
<ul>
  <li id="foo" repeat="template" repeat-start="3">
    <input type="text" name="bar==[[foo]]==" value="[foo]">
    <input type="remove">
  </li>
</ul>
<p><input type="add" template="foo"><input type="submit"></p>
</form>

The remove button will automatically remove the repetition it is associated with, without the need for any JavaScript code. Similarly, the add button will add another repetition to the bottom of the form, increasing the id number.

%5BRepeat%5D

See the WHATWG Web Applications specification [WEBFORMS] for more info.

Cross-document messaging

The WhatWG Web Applications specification defines a set of interfaces for cross-document messaging. A script in one document can create a message and dispatch it to another document, for example the contentDocument of an iframe element. Example modified from the WHATWG Web Applications spec [WHATWG]:

var iframe = document.getElementsByTagName('iframe')[0];
iframe.contentDocument.postMessage('foo');

The receiving document must listen for messages by having added a message event listener:

document.addEventListener('message', receiver, false);
function receiver(e) {
  if (e.domain == 'example.com') {
    displaySelection(e.data);
  }
}

The domain property exists to prevent cross-site security issues. It is recommended to always check this property before processing the message data. Note that in order to use this technology, you must already have a reference to the target document, such as is the case with iframes.

See the WHATWG Web Applications specification [CROSSDOC] for more information.

Multimedia

SVG - Scalable Vector Graphics

SVG is an application format based on vector graphics expressed in XML syntax. As opposed to raster images like JPG and GIF which color individual pixels, vector graphics just describe shapes that appear in the image, like circles, rectangles and paths. One benefit of this is the abillity to scale the image. Developers can apply various filters to create visiual effects.


<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg">
  <g>
    <rect x="10" y="10" width="100" height="100" stroke="red" fill="blue"/>
    <circle cx="20" cy="30" r="15" stroke="green" fill="yellow"/>
  </g>
</svg>

Elements of SVG documents can be animated. SVG also has a DOM, which means the document itself can be manipulated. Like the HTML DOM, the SVG DOM supports events triggered by the user, for example clicks and key presses. SVG also has its own set of CSS style rules, for example for controlling the stroke or fill of an element. In many ways SVG resembles Flash, allthough in an open format.

See the SVG specification [SVG] and further articles on Dev Opera

Canvas

The canvas differs from SVG in that it is an area of pixels to paint on, not a definition of shapes. It is represented by the canvas element in HTML5 [WHATWG]. The element can be programmatically accessed and manipulated through JavaScript, in much the same way as working with the Graphics object in Java. Canvas has strokes, fills, opacity, transformations, paths, global composite operations and many other features to make for a powerful drawing technology.

var canvas = document.getElementById('canvas');
if ( ! canvas.getContext ) { return; }
var c = canvas.getContext('2d');
c.strokeRect(10,10,100,100);
c.fillStyle = 'red';
c.fillRect( 20, 20, 80, 80 );
c.fillStyle = 'rgba(0,255,0,0.6)';
c.fillRect( 30,30,60,60);
c.beginPath();
c.moveTo(60,60);
c.lineTo(65,60);
c.lineTo(65,65);
c.lineTo(55,65);
c.lineTo(55,55);
c.lineTo(70,55);
c.lineTo(70,70);
c.lineTo(50,70);
c.lineTo(50,70);
c.libar#refs_svgneTo(50,50);
c.lineTo(75,50);
cspan class=.quadraticCurveTo( 85,60, 75,75 );
c.lineTo(45,75);
c.quadraticCurveTo( 40,60, 45,45 );
c.lineTo(80,45);
c.stroke();

The canvas can be animated by using the setTimeout and setInterval functions in JavaScript. Typically, one would clear the canvas for each step and draw a new step in the animation.

See the following links for more information:

  • WHATWG Web Application specification: Dynamic canvas [CANVAS].
  • Example of image manipulation at virtuelvis.com [VIRTUELVIS].
  • The Opera 2dgame context [OPERA2DGAME].

The Audio object

Audio can ble played using the Audio object in JavaScript. This object is specified in the Web Applications specification, which is a working draft. However, Opera already supports it.

a = new Audio ( 'sound.wav' );
a.onload = function () {
  a.loop();
  a.play();
  a.stop();
}

An onload event handler is used to determine that the entire clip has been loaded before playing it. Calling loop() will play the sound on infinte loop once it's started. The loop method can be called with an argument signifying the number of times to loop.

See the WHATWG Web Applications specification [WHATWG] for more information.

References

[HTML4]
"HTML 4.01 - W3C Recommendation", "HTML 4.01 - W3C Recommendation" is available at http://www.w3.org/TR/html4
[XHTML]
"W3C Recommendation", "W3C Recommendation" is available at http://www.w3.org/TR/xhtml1/
[OPERADOCTYPE]
"DOCTYPE handling in Opera", "DOCTYPE handling in Opera" is available at http://www.opera.com/docs/specs/doctype/
[XML]
"XML 1.1 - W3C Recommendation", "XML 1.1 - W3C Recommendation" is available at http://www.w3.org/TR/xml
[DOM2]
"DOM Level 2 Core - W3C Recommendation", "DOM Level 2 Core - W3C Recommendation" is available at http://www.w3.org/TR/DOM-Level-2-Core/
[DOM2EVENTS]
"DOM Level 2 Events - W3C Recommendation", "DOM Level 2 Events - W3C Recommendation" is available at http://www.w3.org/TR/DOM-Level-2-Events/
[DOM2HTML]
"DOM Level 2 HTML - W3C Recommendation", "DOM Level 2 HTML - W3C Recommendation" is available at http://www.w3.org/TR/DOM-Level-2-HTML/
[DOM2STYLE]
"DOM Level 2 Style - W3C Recommendation", "DOM Level 2 Style - W3C Recommendation" is available at http://www.w3.org/TR/DOM-Level-2-Style/
[DOM3]
"DOM Level 3 Core - W3C Recommendation", "DOM Level 3 Core - W3C Recommendation" is available at http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/
[DOM3LS]
"DOM Level 3: Load and Save - W3C Recommendation", "DOM Level 3: Load and Save - W3C Recommendation" is available at http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/
[W3CDOM]
"DOM activities at the W3C", "DOM activities at the W3C" is available at http://www.w3.org/DOM
[ECMASCRIPT]
"ECMAScript Specification", "ECMAScript Specification" is available at http://www.ecma-international.org/publications/standards/Ecma-262.htm
[HOWTOJS]
"JavaScript tutorial at HowToCreate.co.uk", Mark 'Tarquin' Wilton-Jones, "JavaScript tutorial at HowToCreate.co.uk" is available at http://www.howtocreate.co.uk/tutorials/javascript/
[EFFJS]
"Efficient JavaScript code at dev.opera.com", Mark 'Tarquin' Wilton-Jones, "Efficient JavaScript code at dev.opera.com" is available at http://dev.opera.com/articles/view/efficient-javascript/
[CROCKFORD]
"JavaScript resources at crockford.com", Douglas Crockford, "JavaScript resources at crockford.com" is available at http://www.crockford.com/
[CSS2]
"CSS 2.1 - W3C Recommendation", "CSS 2.1 - W3C Recommendation" is available at http://www.w3.org/TR/css2/
[W3CSTYLE]
"Style activities at the W3C", "Style activities at the W3C" is available at http://www.w3.org/Style
[W3CCSSCUR]
"Current CSS work at the W3C", "Current CSS work at the W3C" is available at http://www.w3.org/Style/CSS/current-work
[XSLT]
"XSLT 1.0 - W3C Recommendation", "XSLT 1.0 - W3C Recommendation" is available at http://www.w3.org/TR/xslt
[XHR]
"XMLHttpRequest - W3C Working Draft", "XMLHttpRequest - W3C Working Draft" is available at http://www.w3.org/TR/XMLHttpRequest/
[SVG]
"SVG 1.1 - W3C Recommendation", "SVG 1.1 - W3C Recommendation" is available at http://www.w3.org/TR/svg
[WHATWG]
"Web Applications 1.0 - WHATWG Working Draft", "Web Applications 1.0 - WHATWG Working Draft" is available at http://www.whatwg.org/specs/web-apps/current-work/
[WEBFORMS]
"Web Forms 2.0 - WHATWG Working Draft", "Web Forms 2.0 - WHATWG Working Draft" is available at http://www.whatwg.org/specs/web-forms/current-work/
[CROSSDOC]
"Cross document messaging, from the Web Applications 1.0 working draft", "Cross document messaging, from the Web Applications 1.0 working draft" is available at http://www.whatwg.org/specs/web-apps/current-work/#crossDocumentMessages
[AUDIO]
"The Audio Object, from the Web Applications 1.0 working fraft", "The Audio Object, from the Web Applications 1.0 working fraft" is available at http://www.whatwg.org/specs/web-apps/current-work/#sound
[CANVAS]
"WHATWG Wep Applications: Dynamic canvas element", "WHATWG Wep Applications: Dynamic canvas element" is available at http://whatwg.org/specs/web-apps/current-work/#scs-dynamic
[VIRTUELVIS]
"Examples of image manipulation at virtuelvis.com", Arve Bersvendsen, "Examples of image manipulation at virtuelvis.com" is available at http://virtuelvis.com/archives/2005/12/canvas-image-manipulation
[OPERA2DGAME]
"Blog post on the Opera 2dgame canvas context", "Blog post on the Opera 2dgame canvas context" is available at http://my.opera.com/WebApplications/blog/show.dml/200788
XML 1.1 - W3C Recommendation

This article is licensed under a Creative Commons Attribution, Non Commercial - Share Alike 2.5 license.

Comments

The forum archive of this article is still available on My Opera.

No new comments accepted.