JavaScript badge to present Twitter reactions to a certain URL in your own web site

With a blog it’s great getting comments, but as any blogger need to realize, there are other channels that people like to express their reactions in to – especially Twitter.

Background

Therefore, I wanted a nice way to implement reactions on Twitter to my blog posts, so everyone reading could see it all in the same context. Some time ago (maybe a year) I found the BackType Connect plugin for WordPress.

All good and well, till it stopped working a few months ago. I went through all of my settings, checked server and plugin rights etc to see where the problem was. I also e-mailed the BackType support team and never got a reply. Eventually, by chance, I found a blog post by the Backtype team proclaiming that they had retired their WordPress plugin, without any notice whatsoever to all of its users.

What bugs me even more is that you can still download the plugin from their own web page without any information about this, and it is still easy to find in WordPress own listing of plugins.

That is really really bad, and definitely not a responsible way to handle code. I don’t ask for them to support it anymore, I’m sure they had good reasons to move on and focus on other things. But, not letting end users know and still having it publicly available really sucks, in my opinion.

Looking at options

Therefore, I needed to start looking at options. Something that is really popular these days is DISQUS for general comment handling, handling things such as Twitter reactions etc. However, I really didn’t feel attracted by syncing comments to another service, getting loads of scripts and invalid code in my blog generated by them etc (I tried it on my blog, and besides from all the superfluous code, it broke my entire layout with a generated stray end div tag…).

I wanted something really lightweight with only the necessary code to show Twitter reactions, so I decided to implement it as a JavaScript badge, generated from JSON data. Therefore, I looked directly at the Twitter Search API where I could get this data. All worked good and well, but Twitter Search only supports searching from today and a week back in time, and naturally I wanted reactions from a longer timeline than that.

That’s when I started looking at Topsy and their Otter API. The really good thing about Topsy is that it supports finding tweets all the way back to 2008 and getting them returned as JSON, which is awesome!

Using Topsy/Otter API to find trackbacks

Now when I had found a service that would deliver what I needed, I delved deeper into it to create my Twitter reactions JavaScript badge. It is based on JSONP, which is returned JSON data, but wrapped with a function call, so it would call a function in my web site with the JSON data so I could iterate over it and present the tweets. Like this:

	twitterReactions({"Data": "My name is JSON"});

Getting the JSONP code is as simple as including a script element in your web page, set its src to the Otter API URI and pass the URL you want Twitter reactions to as a parameter:

	<script src="http://otter.topsy.com/trackbacks.js?callback=twitterReactions&perpage=100&url=http://robertnyman.com/2010/10/22/introducing-html5-web-sockets-taking-bidirectional-communication-on-the-web-to-the-next-level-2/"></script>

As you can see in the above code, I have three parameters:

callback
The JavaScript function in my page that I want to use to process the JSON data.
perpage
How many results per page (i.e. total results) I want in the returned JSON. I want it all in the same page, and currently the maximum supported number is 100 tweets. A shame with that limitation right now (I think Twitter’s own limit is 1500), but I don’t have many posts with over 100 Twitter reactions, so for now I can live with that.
url
The URL, i.e. address to my blog post, that I want to find Twitter reactions for.

There are also a number of other parameters if you want to tweak things even more.

Creating the JavaScript badge

Now that we know how to get Twitter reactions as JSONP, let’s look at how we create our badge to present those tweets. What we need first is an HTML element in which we want to show those reactions:

	<div id="twitter-reactions"></div>

As you see, I leave this element empty so nothing is shown if it fails – however, if you want to you could have some fallback content there.

Then, in your web page, or preferably in an included JavaScript file, add the twitterReactions function we specified before to handle the response:

function twitterReactions (json) {
	// Checking the JSON response
	var results = json.response.list;
		
	// If there are any results, iterate over them			
	if (typeof results !== "undefined") {
		var resultsLength = results.length,
			twitterReactionsPresenter = document.getElementById("twitter-reactions"),
			twitterReactionsHeader = document.createElement("h3"),
			tweets = '
    ', twitterReactionsText = resultsLength + " Twitter reaction" + ((resultsLength > 1)? "s" : ""), current, currentAuthor, tweet; // Creating header before tweets container twitterReactionsHeader.id = "twitter-reactions-header"; twitterReactionsHeader.innerHTML = twitterReactionsText; twitterReactionsPresenter.parentNode.insertBefore(twitterReactionsHeader, twitterReactionsPresenter); // Iterating over all tweets for (var i=resultsLength-1; i>=0; i--) { current = results[i]; currentAuthor = current.author; tweet = '
  • '; tweet += ''; tweet += '' + currentAuthor.nick + " (" + currentAuthor.name + ")" + "
    "; tweet += current.date_alpha; tweet += '
    ' + current.content.replace(/(http:\/\/[\w\.\d%\/\-\_]+)/gi, '$1') + '
    '; tweet += '
  • '; tweets += tweet; } tweets += '
'; // Apply all tweets into the tweet presenting element twitterReactionsPresenter.innerHTML = tweets; } }

I think that code is pretty self-explanatory. It checks the JSON data if there were any results, and if yes, it creates a heading and applies it before the Twitter reactions HTML container element with a reaction count. Then it iterates over all the reactions and creates HTML elements for them and when it’s done, it applies the entire HTML chunk into the web page.

I wanted this very simple code to be JavaScript-library agnostic, but you could of course use a JavaScript library or native DOM methods (*shivers*) to create the elements as real DOM elements instead of as an HTML string. For me, though, this is all good.

Then, as we saw above, after our twitterReactions function has been declared, we include the script file to get the JSONP data:

	<script src="http://otter.topsy.com/trackbacks.js?callback=twitterReactions&perpage=100&url=http://robertnyman.com/2010/10/22/introducing-html5-web-sockets-taking-bidirectional-communication-on-the-web-to-the-next-level-2/"></script>

And there we have it! A fully functional JavaScript badge to get Twitter reactions to any URL we put in.

Demo of the Twitter reactions JavaScript badge

You can take a look at the demo of the Twitter reactions JavaScript badge and see how it gets reactions for a certain URL. Just take the code in this blog post or the demo page and create your own badge and tweak it to your own needs.

Happy getting-twitter-reactions day! :-)

Posted in Developing,JavaScript,Technology |

15 Comments

  • Lars Gunther says:

    A quick queston. Will it work for bit.ly, tr.im and other url-shorteners as well?

    What I mean is, if a page is referenced in a tweet, but only through this indirect linking, will it still be picked up?

  • Robert Nyman says:

    Lars,

    Yes, it does! I can’t find the link right now, but I think Topsy support 188 URL shorteners or so, and will look up the original URL.

    As you can see for the Twitter reactions to this blog post, they are all found through URL shorteners.

  • Tome Cvitan says:

    Found a minor bug in the script – currentAuthor.url contains the full url :)

  • [...] This post was mentioned on Twitter by Lim Chee Aun, Robert Nyman, Web RSS News, victor foster, Michael Beckius and others. Michael Beckius said: I gotta try this: RT @robertnyman JavaScript badge to present Twitter reactions to a certain URL in your own web site: http://bit.ly/hBrG34 [...]

  • Lars Gunther says:

    @Robert

    It seems to pick up tweets using URL-shorteners, but did a little more extensive test, trying out the case where I reference a specific comment, using and URL with a fragment. So far my tweet has not been picked up.

    But maybe that’s asking too much from any service.

    The best solution would of course be if Twitter would let users submit proper links the [a href=""] way, and not have the URL characters counted at all.

  • It looks like you might have some XSS bugs in there (depending on the services correctly strips everything).

    A word of advice. Do not use innerHTML with data from untrusted sources. Use createElement, textContent etc.

  • Tino Zijdel says:

    Although technically a nice feature (and a great explanation with that), what you get from Twitter isn’t much more than trackbacks (you do use that term in one of your subheaders) instead of real reactions, and I’ve always failed to see the added value of those for other readers. Especially in the case of Twitter when the trackback is mostly just a mere mention of your post on twitter without any other feedback.

    Besides that I wouldn’t want to be dependent on another medium for actual useful comments; you should encourage people to post those comments on the blog itself.

    So sorry for being a critic; this is still a very good post and I’m sure it will be of use to some people :)

  • As Tome Cvitan says: currentAuthor.url contains the full url.
    <a href=”http://twitter.com/’ + currentAuthor.url + ‘”> should be <a href=”‘ + currentAuthor.url + ‘”>

    I would also add .\-\ to the regular expression to allow urls inside the tweets to contain -

  • Forgot to say, great example of using the topsy otter API.

  • Robert Nyman says:

    Tome,

    Ah! I removed that before, but apparently managed to reintroduce it. Fixed now, in the post and the demo example.

    Thanks!

    Lars,

    Hmm, yeah, no that won’t work. Agree about links, but don’t think it will ever happen with Twitter.

    Erik,

    Thanks for the concenrn. XSS and trusting services is always a risk, but in this case I made the deliberate choice of trusting Topsy – also createElement etc are options for those who want to.

    Thanks for pointing it out, though!

    Tino,

    Thanks!
    It’s true that it is mostly trackbacks, but in the good cases there is also a comment to accompany it. I think in pure trackbacks/retweet scenarios, though, it still adds some value being a sort of Twitter Like-button.

    It could be nice to find other people who like the same post, to see how popular the post is in itself (posts can have just one comment and then 100 Twitter reactions – if people only saw the one comment, it could make it harder to determine if other people like it/agree or not).

    But yes, at the end of the day, I guess it’s in the eye of the beholder. :-)

    Ludvig,

    Thank you!
    And yep, author URL bug fixed and improved regular expression for URLs.

  • You should be careful when using such plugins, like those connecting to remote sites.

  • Robert Nyman says:

    Victor,

    Absolutely. It’s up to you if you trust that web site or not.

  • [...] a tweet button, a certain amount of heavy lifting is involved to include Twitter reactions:  manual scripting, a custom script or a third-party tool is [...]

  • Support says:

    Yay ! Above Demo URL link is broken , i tried this site link on Firefox, Chrome, IE. Same prob . Could this be fixed.

  • [...] a tweet button, a certain amount of heavy lifting is involved to include Twitter reactions:  manual scripting, a custom script or a third-party tool is [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>