All Posts in html5

August 15, 2014 - Comments Off on How to Build an Easy Embedabble Widget

How to Build an Easy Embedabble Widget

Building with iframes is a fantastic way to create seamless, easy to implement, embeddable widgets. Once set up, creating multiple instances linking to your service is easy to do. Existing within a website, an iframe is like a window onto another website. Rather than forcing open another window, a user can interact with another service within the context of the website they have navigated to.

Over here at The Mechanism, we have been using iframes to integrate our custom bug tracking solution with client websites during user assisted testing. We needed an inconspicuous tool which would allow clients to seamlessly review work and submit bugs as they find them.

The requirements for this front end bug catcher:

  1. Simple to embed and easy to implement across many projects
  2. Sandboxed so that it doesn't cause any conflicts with the project DOM, JS or CSS
  3. Simple architecture which works on all browsers
  4. Responsive; it must work on all device sizes and form factors
  5. Context Aware; diagnostic information will require knowledge of the parent document (the website under bug tracking )

Our first iteration of the bug tracking widget violated the second requirement. For our first prototype, we loaded a script and pulled in our view and styling files through JSONP (a method for circumventing Same-Origin Policy, you can read about it here). This worked in our limited prototype but caused a few issues. First of all, we had to give our DOM elements verbose ID's and class names to ensure there would no conflict with the parent document. Secondly, we ran the risk of causing script conflicts with our dependencies. We used a script loader to minimize this risk, however we could never be sure. Finally, we were at the mercy of the stylesheets loaded by the parent which required us to write additional resets to ensure consistent appearance across projects. However, repairs like this are equivalent to bailing a sinking ship rather than repairing the leak.

So for our second iteration we converted the widget into an iframe. To do so we still had to find a way to get around the Same-Origin Policy. The Same-Origin Policy restricts communication between two documents; the parent window and the iframe. Cross Document Messaging is a new addition to the HTML5 specification, which allows for simple string communication between documents. This is supported by most modern browsers, however, there are many hacks necessary for older browsers.


easyXDM is a great library built to cross this great divide introduced by iframes. It uses the HTML5 postMessage() method when available and uses many fallbacks when necessary, ensuring the free flow of information between documents. For the developer, it exposes two protocols for data transfer. The first is a socket, which will send a string between the documents. This method requires us to parse and decipher the string before performing the relevant action on that information. The second option is an RPC (Remote Procedure Call), specifically JSON-RPC. JSON-RPC is a specification for calling functions from remote software, and for data to be returned. This allows for a much more dynamic interaction between our two documents where each process exists in their relative scope and can communicate as discreet functions would be expected. For our needs, the simpler option and the one we will be employing is the RPC protocol.

To implement easyXDM we must load our dependency and create an RPC instance, with the necessary proxy objects and method stubs. We will initiate this within a script loaded on the parent document. This script will embed our iframe and act as our gateway to the bug tracking widget.

On our parent document we will place an asynchronous script call to our remote script


// footer.html


In our script we will start by loading our easyXDM dependency


// main.js

var serverURL = '',

iframeFile = 'iframe.html',

depends = {

'easyXDM': serverURL + 'js/easyXDM.min.js'


Object.size = function(obj) {

var size = 0, key;

for (key in obj) {

if (obj.hasOwnProperty(key)) size++;


return size;


var scriptCount = Object.size(depends); // count of scripts required

var scriptLoads = 0; // count of script loaded

for (var key in depends) {

if (depends.hasOwnProperty(key)) {

loadScript(key, depends[key], function() {


if (scriptLoads === scriptCount) {






function loadScript (dependency, src, callback) {

// this function checks if the dependency is present.

// it waits for load before executing the callback.

if (window[dependency] === undefined) { // if dependency is not present

var scriptTag = document.createElement('script');

scriptTag.setAttribute('type', 'text/javascript');

scriptTag.setAttribute('src', src);

if (scriptTag.readyState) {

scriptTag.onreadystatechange = function () { // For old versions of IE

if (this.readyState == 'complete' || this.readyState == 'loaded') {




} else { // Other browsers

scriptTag.onload = callback;


(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);

} else {





  1. Lines 1-5 we are declaring a some variables that will be used later.
  2. Lines 7-16 we extend the Object object with a method which will return the length of our depends array on line 15, along with a variable to hold an index value.
  3. Lines 18-27, we run a loop through the depends array and call a function loadScript(), which takes the name of our dependency, the url it can be found at and a callback which will be run once the dependency is loaded.
  4. Lines 29-49, our function which will test the presence of the dependency and load the script if it is not found. It uses various methods to ensure the script is loaded before running the callback function.

Next we will create our RPC instance which will load the iframe


// main.js




var iframeContainer = document.createElement('div'); = 'fixed'; = 999; = 0; = 0; = "auto"; = "auto";['max-height'] = '100%';['max-width'] = '100%';


var rpc = new easyXDM.Rpc({

remote: serverURL + iframeFile,

container: iframeContainer,

props: {

id: 'bug-iframe',

frameborder: '0',

scrolling: 'no',

marginwidth: '0',

marginheight: '0',

allowTransparency: 'true',

style: {

height: '100%',

width: '100%',

display: 'block'





local: {

resizeiFrame: function (widthReq, heightReq, allowScroll) {

var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,

windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

var width = (widthReq < windowWidth) ? widthReq : windowWidth;

var height = (heightReq < windowHeight) ? heightReq : windowHeight; = width + 'px'; = height + 'px';

var sc = (allowScroll) ? 'yes' : 'no';

document.getElementById('mech-bug-iframe').scrolling = sc;

return {

x: width,

y: height



parentInfo: function () {

return {

width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,

height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,

url: window.location.href






  1. Lines 5-16; we are creating the iframes container with properties for it's layout within the parent documents DOM
  2. Lines 18-34; our RPC instance with the address to find the iframe contents, a container to place the div in, and some properties to control it's appearance
  3. Lines 34-64; is where we declare the methods we will be exposing to our iframe. resizeiFrame() and parentInfo() will allow us the adjust the size of the iframe and return diagnostic information respectively. They will be called from within our iframe

In our iframes markup we will load easyXDM and a shiv for older browsers without support for JSON, plus another .js file where we will instatiate our RPC connection.



In our iframe-main.js file, we will create another instance of easyXDM.Rpc and create stubs for our remote methods


// iframe-main.js

var rpc = new easyXDM.Rpc({},


remote: {

resizeiFrame: {},

parentInfo: {}






rpc.parentInfo(function(parentInfo) {

var diagObject = {

'width' = parentInfo.width,

'height' = parentInfo.height,

'url' = parentInfo.url




  1. Lines 2-8; we create our rpc object with the relevant stubs, referring to the remote methods
  2. Lines 14-20; an example of how we call our remote function. Notice the anonymous function we pass to the remote function to return our requested data. This is an asynchronous function

Stay tuned for more on the Venus project to find out where it goes next. Dhruv Mehrotra will be back in a few weeks with a blog post going over some of the steps taken to set up the Ruby on Rails server behind Venus. And we will have meetup at our offices the second week of September. Hope to see you there!

Published by: georgebrassey in The Programming Mechanism
Tags: , , , ,

August 5, 2011 - Comments Off on The Thinking Mechanism – 8/5/11

The Thinking Mechanism – 8/5/11

The Thinking Mechanism is a series of weekly posts, published on Fridays, covering the ideas The Mechanism is thinking and talking about with our peers and clients.

The week in quick links:

A recent study determined the most influential person on Twitter is a Brazilian comic you've never heard of.

• The interactive trailer for BBC Earth's film One Life is fantastic.

2011 Emmy Nominations for Outstanding Main Title Design. - The best in storytelling motion graphics.

Adobe previews Edge, an HTML5 tool.

The Expressive Web is the companion showcase site to Adobe's Edge.

• Getting Bin Laden - What happened that night in Abbottabad. by Nicholas Schmidle for The New Yorker. -  "The teams had barely been on target for a minute, and the mission was already veering off course."

• Facebook Buys E-book Maker Push Pop Press, Plans to Integrate its Tech.

This American Life, When Patents Attack - "Why would a company rent an office in a tiny town in East Texas, put a nameplate on the door, and leave it completely empty for a year? The answer involves a controversial billionaire physicist in Seattle, a 40 pound cookbook, and a war waging right now, all across the software and tech industries."

July 1, 2011 - Comments Off on The Thinking Mechanism – 7/1/11

The Thinking Mechanism – 7/1/11

The Thinking Mechanism is a series of weekly posts, published on Fridays, covering the ideas The Mechanism is thinking and talking about with our peers and clients.

Right before we all have a holiday weekend to spend time face to face with our circle of friends Google makes several announcements concerning the social web:

Google+, their next foray into social networking after Orkut and Buzz, has a distinctly micro-social approach and user-friendly privacy settings. The fact that you can easily download any content you input into it and can easily delete your account with one click, if you chose to do so, proves that Google intends to compete with Facebook by providing ease of use. Click here to see the introductory videos. Click here to read a comprehensive look at the launch by Steven Levy of Wired Magazine.

• Google Analytics now features Social Interaction Tracking. Update your Analytics code and get full activity reports on all your social media buttons, including +1, Like, Tweet.

Google Takeout allows you to download a copy of your data stored within Google products.

Google Swiffy is not directly related to social networking, instead it lets you upload a swf file and convert it to HTML5. More HTML5 sites means access to the web in more mobile devices and more content to share on Google+.

• Let's not forget about Google search, they've also announced a collaboration with the Getty Museum to allow visual searches of artworks.

What Do You Love? A new page that shows you the results of your search across all Google products in one location.

• On the other side of the social spectrum, Facebook is quietly testing their first major redesign in over a year. The new design, which some of us are already experiencing live, feature an additional "What's Happening Now" Twitter-like stream besides the News Feed and will have navigation and advertising elements remain static on the page as you scroll down.

• And lastly, in honor of the Fourth of July: how fireworks and sparklers are made.

November 20, 2009 - Comments Off on Live blogging Standards.Next: Future of Internet Explorer

Live blogging Standards.Next: Future of Internet Explorer

Pete LePage
Senior Product Manager, Developers & Security for IE

IE 8

IE 8 is a hybrid, has two engines; IE 9 will have three engines: IE 7, IE 8 and IE 9. This way can ensure site works in future versions of the browser. This is just one of the many wonders that the fourth industrial revolution had brought with us.

IE 8 supports session and local storage (see presentation by Marcus Lofthouse to the New York Web Standards Meetup). Added addition to spec: a way to remove all.

Mutable DOM prototypes: take a DOM element and add properties/methods to it. Add method to img. There are a number of things not implemented in IE 8. Can write a chunk of JavaScript that adds functionality to browser. This will be used by people writing the JavaScript frameworks (jQuery, Dojo).

Native JSON support.

Network events

CrossDocumentMessaging and CrossDomainRequest

Selectors API

Fixed getElementById.

Demos at (browser-sniffs and only wants to work in IE 8).

IE 9

  • Faster; speed is important. Finally comparable to FF.
  • A lot of work on standards-support. Will implement border-radius. Acid3 score went from 20 to 32. IE 8 Current CSS3 support is vertical-text. Hope to more than double it in IE 9. 😉


Q: Why always trying to play catch up? Why not just adopt Webkit?

A: A lot of things that make adopting Webkit or Gecko more difficult than it seems.

Q: Any release date for IE 9?

A: No dates as of now

Q: Still trying to get Canvas out of the spec for HTML5?

A: Not sure; might be a miscommunication

Q: Any major updates planned for IE 8?

A: Probably not; next major version will be 9. Security updates will be released for 8, but the rendering engine will not change.

Published by: jeffreybarke in The Programming Mechanism
Tags: , , ,

November 19, 2009 - Comments Off on Live blogging New York Web Standards Meetup—HTML5 part three

Live blogging New York Web Standards Meetup—HTML5 part three

HTML5 Part Three: Session, local storage, Web databases, and application cache

Marcus Lofthouse ( will continue the HTML5 series by exploring the following web storage techniques:

  • Session and Local Storage—providing a javascript accessible interface to key-value storage.
  • Web Databases—relational database support for storing structured data inside the browser.
  • Application Cache—providing the ability to define a list of files the browser should store locally and not request from the server again (until you explicitly signal the browser that you have something new to offer). Strategically used, this allows for the creation of web applications that can be used completely offline.

HTML5 storage techniques

  • Session/local storage
  • Client-side browser databases
  • Application cache

Current techniques

  • Server-side storage
  • Cookies: often used for customization
  • Plugins (Google Gears): Not used as extensively as server-side storage or cookies

Some issues (server side)

  • Requires persistent connection to the internet
  • Large data sets have to be downloaded each time the page is loaded
  • Can be processing intensive

Some issues (cookies)

  • Difficult to work with in JavaScript
  • Get sent to and from the server with each request (whether used or not)
  • Limited to 4k depending on the browser

Session storage

  • Allow 5–10 mb of storage
  • Works in Firefox, Safari and IE 8
  • Easy to use

Using session storage

sessionStorage.setItem(key, value);
sessionStorage['key'] = value;
sessionStorage.key = value;

Local storage

  • Exactly the same—only different
  • Different in scope & persistence

Session storage scope

  • Accessible only to one instance of a browser tab or window
  • All data is destroyed when window is closed
  • Newly created windows or tabs will get a unique copy of sessionStorage; they will diverge from that point forward
  • Prevents data leaking between windows

Local storage

  • Accessible to all windows or tabs (for site—obeys same origin policy)
  • Persistent storage between browser restarts

The base features are the same cross-browser, but each browser has its own specific extensions.

More than simple key-value pairs; can also store large chunks of XML or JSON.

Client-side database

  • Provides persistent storage of well structured data
  • Currently only supported in Webkit

Comments and concerns

  • No standard web SQL dialect
  • SQLite doesn't enforce types
  • SQLite doesn't enforce data lengths


  • Asynchronous DB calls keep the UI responsive
  • JS interface provides an easy way to clean your data and avoid SQL injection attacks
  • All database calls wrapped in transactions
  • Database versioning

Opening a database

var name = 'cheesedb';
var version = '1.0';

Execute SQL statements; two flavors

executeSQL(sqlStatement, arguments);
executeSQL(sqlStatement …

Security issues

  • Same origin policy
  • Tools can allow users to modify their own local data.

What is an application?

  • Desktop: compiled source, images, config/data files
  • WebApp: HTML, images, CSS, JavaScript, config/data files
  • Largest difference is delivery mechanism: webapps require you to access the sources via the internet

Application cache

  • Allows you to instruct the browser to keep a local copy of a set of files.
  • These files can be used offline, but more importantly won't request the resource from the server until told to do so again.
  • If you specify all of the files needed to run your application you will be able to run it offline.

Application caching

  • Cache manifest

Cache manifest

  • Simple text file
  • First line contains CACHE MANIFEST
  • Following lines contain paths to files to be cached
  • Document is declared as HTML5: <!DOCTYPE html>
  • The cache manifest file is served with …
  • New attribute for the html element: <html manifest="cache.manifest">
  • The cache manifest automatically includes the file it is called from.

Other options

  • Network section for content never to be cached

Updating cache manifest

  • Browsers check to see if the cache file has been updated by doing a byte by byte comparison of the cache manifest file, not by looking to see if the server resources have been updated
  • If the file has been changed the browser will download the new assets in the background
  • Cache updating is atomic. If any file is not found, the cache manifest will re-download everything (304 or 200 requests).

Batteries about to fail; signing out

Published by: jeffreybarke in The Programming Mechanism
Tags: , ,

October 5, 2009 - Comments Off on New York Web Standards Meetup—HTML5 part two (links and resources)

New York Web Standards Meetup—HTML5 part two (links and resources)

Links to resources from last month's HTML5 Part Two: Canvas, Web Forms 2.0, Audio and Video presentation to the New York Web Standards Meetup by Mike Taylor (TuenCore) and Jeffrey Barke (theMechanism). Thanks to everyone who attended!

See also:

Published by: jeffreybarke in The Thinking Mechanism
Tags: , , ,

September 2, 2009 - Comments Off on NY Web Standards Meetup—HTML5 part one

NY Web Standards Meetup—HTML5 part one

August 27, 2009 - Comments Off on Liveblogging the New York Web Standards Meetup—Getting started with HTML5

Liveblogging the New York Web Standards Meetup—Getting started with HTML5

Mike Taylor ( will give a brief overview of (the current state of) HTML5, focusing primarily on browser support, new elements and their corresponding semantics and getting CSS to play along. He will also review how the front-end team at TuneCore is implementing these new features into a production site today.


What is HTML5?

And why should I care?

HTML5 is the next version of HTML; primarily aimed at web applications. Began as the Web Applications Spec in a W3C Working Group.

Why going back to HTML, why not continuing XHTML? We're not; HTML5 is both HTML and XHTML. Can write it either way you prefer.

  • New semantic elements
  • Rich DOM APIs (local storage, native drag & drop, content editable fields, web forms 2.0)
  • Rich embedded content (<audio>, <video>, <canvas>)

Mike personally finds the web forms 2.0 the most exciting. Opera 10 is the only who currently supports web forms 2.0.

In this talk, primarily going to cover new semantic elements.

Read more

Published by: jeffreybarke in The Programming Mechanism
Tags: , ,

June 26, 2008 - Comments Off on Standards Suck: ARIA in HTML5

Standards Suck: ARIA in HTML5

During XTech2008, Anne van Kesteren and Marcos Caceres sat down to chat about the current state of the "ARIA in HTML5" debate. Anne gives an overview of ARIA and the controversy over naming of ARIA attributes and makes some suggestions as to how the community can move forward.

Part One:

Part Two:

Source: YouTube: Part One | Part Two

Jeffrey Barke is senior developer and information architect at theMechanism, a multimedia firm with offices in New York, London and Durban, South Africa.

Published by: jeffreybarke in The Programming Mechanism
Tags: , ,