How to build your own shareable HTML5 widgets

I have, in the past, had a need to create a javascript wrapper that creates an iframe to load content from an external website. As many of you know you cannot load content from a domain other than your own via AJAX due to modern browsers enforcing the same origin policy (there are work arounds, but that’s beyond the scope of this post). I thought that this code would be useful to others too, so I’ve modified it slightly to make it more universal and configurable.

There are 3 parts to this implementation. The first is the code on the end-user’s page:

The div is a wrapper for the widget you’re building. The javascript include should link to a copy of widget.js on your own server. This is the second part – the javascript that creates an iframe and loads your external content.

As you can see, there are 4 variables you can set at the top. The first one specifies the id of the enclosing div we just created. The second one is the URL to the external content. The third and fourth are the height and width of the iframe.

Because the iframe has no knowledge of the dimensions of the content it is loading, you have to set the iframe’s height and width. The final part of the puzzle is your widget of course. This is up to you to build something…

Onc feature of this shareable widget is the ability to specify data-* attributes in the div wrapper. The widget.js passes these attributes to your widget script as GET variables which is handy. So in the example above, data-variable1=”abc” and data-variable2=”xyz” translate to get variables: variable1 => abc and variable2 => xyz. Pretty neat eh?

With this code, you’ll be building shareable HTL5 widgets in no time…have fun!

Leave a Reply