Displaying a Twitter Timeline with OAuth Authentication in JavaScript

(The article was lost due to server trouble, so I rewrote it.)

With the change from Twitter REST API 1.0 to 1.1, OAuth authentication became necessary for all API use, and version 1.0 was completely shut down on June 12, 2013. I needed to display a user’s timeline with client-side JavaScript and wrote code supporting OAuth, but I got stuck with jQuery’s ajax function, so I am leaving this as a memo. Since keys such as the consumerKey are fully exposed, its uses are probably limited.

*What you need

<!DOCTYPE html>
<html lang="ja">
  <head>
   <meta charset="utf-8" />
   <title>Twitter+OAuth+javaScript timeline</title>
   <script type="text/javascript" src="jquery-[version]"></script>
   <script type="text/javascript" src="oauth.js"></script>
   <script type="text/javascript" src="sha1.js"></script>
   <script type="text/javascript" >

function Twitter() {}
Twitter.prototype = {
		consumerKey:	"omitted",
		consumerSecret:	"omitted",
		accessToken:	"omitted",
		tokenSecret:	"omitted"
};
Twitter.prototype.get = function(api, content) {
    var accessor = {
		consumerSecret: this.consumerSecret,
		tokenSecret: this.tokenSecret
    };

    var message = {
		method: "GET",
		action: api,
		parameters: {
			oauth_version: "1.0",
			oauth_signature_method: "HMAC-SHA1",
			oauth_consumer_key: this.consumerKey,
			oauth_token: this.accessToken
		}
    };
    for (var key in content) {
		message.parameters[key] = content[key];
    }
    OAuth.setTimestampAndNonce(message);
    OAuth.SignatureMethod.sign(message, accessor);
    var target = OAuth.addToURL(message.action, message.parameters);

    var options = {
		type: message.method,
		url: target,
		dataType: "jsonp",	//specify jsonp here
		jsonp: false,		//do not let jQuery embed the callback function name
		cache: true			//do not embed the time in the request parameters
	};
    $.ajax(options);
}

var twitter = new Twitter();

function update(data){
	for( var i = 0; i < data.length; i++ ) {
		$("#test").append("<p>"+data[i].user.name + ' : ' + data[i].text+"</p>");
	}
}

$(function(){
	//specify options and callback function
	var content = {count: "50", callback: "update"};
	//call the Twitter API
	twitter.get("https://api.twitter.com/1.1/statuses/home_timeline.json", content)
});

</script>
  </head>
  <body>
<div id="test"></div>
</body>
</html>

home_timeline has a strict limit of 15 calls per 15 minutes (i.e., once a minute) before hitting the rate limit, so if you only need the user’s own posts, switching the API call to user_timeline allows up to 180 calls per 15 minutes.