Doorkeeper
Developer Resources

Creating an Embeddable JavaScript Widget

Overview

This guide will show you how we created a light-weight JavaScript widget for people to embed on their webpages. This example uses Ruby on Rails, but it is not necessary to create the widget.

Example

In Doorkeeper, we let users put the following code into their website.

This code will produce the widget below.

Register for TRBMeetup

Guide

For our widget, we want people to use normal links and then convert them to widgets. That way, even if people don't have JavaScript enabled, they will still be able to follow the link.

To implement our widget we need to do two things that are hard to do in a cross-browser compliant way: find all elements in a page of a certain class name and execute JavaScript after the page is loaded. JavaScript frameworks like JQuery support doing both of these in a cross-browser compliant way, but using such a heavy framework is overkill for our widget. Rather than trying to implement our own workarounds, we use the libraries getelementsbyclassname and domready to handle it for us.

Having these two pieces of the puzzle in place, the actual code for the widget itself is quite straightforward. We simply iterate through each element with the doorkeeper-registration-widget class, and replace it with an iframe with a src attribute that is the destination of the link with /widget.html appended on to it:

One trick we're using above is to wrap everything in an anonymous function. By doing this, we ensure our widget doesn't interfere with any JavaScript on our clients' pages.

Then we have an action on our EventsController to render the event specific widget.

That's pretty much it. If you have any comments or suggestions, please leave them below or fork any of the above Gists.