We’re all familiar with how to embed a Twitter timeline – which is to simply copy the Widget code from Twitter and paste into your site. Twitter then drops in an iframe and you have a timeline.

The alternative is to use the twitter API to pull a timeline and then deal with OAUTH.

Or, you could just scrape a timeline out of the GET response that an iframed timeline’s HREF creates which is what I’ve done here. The key to this working at all is that Twitter’s iframe-embedding method creates a GET request that returns a JSONP payload. JSONP allows developers to circumvent cross domain restrictions which is why embedding a timeline works.

Knowing that I can successfully retrieve timeline data and that the data will be sent to a callback of my choosing (the “P” in “JSONP”) all I needed to do was to parse out the useful information – parse it out because the response we get back is not in JSON notation but a string of html. Parsing is a pain though so I decided to use jQuery to convert the string to a DOM object so that I can search for the nodes by traversing the DOM tree for the bits of information that I need.

Updated 4/11/2016 to reflect the latest Twitter changes

Here’s an example, use the timeline ID below or enter your own.

Note that we’re limited to the 20 most recent tweets. I convert everything to an array of tweet objects as illustrated below:

twttr_updated_jsonp

You can get the code here: https://github.com/r-luna/simple_twitter_timeline or simply view this page’s source.

All you need is the ID of the timeline, a callback of your own making, and jQuery to get this to work.

In this example you can see that the function to get your timeline data is namespaced to twtrUtil. To get your timeline call twtrUtil.getTimeline(CALLBACK_HERE,ID_HERE):

    function handleResponse(o){
        console.log(o);
        $('#response').html(JSON.stringify(o));
    }
        
    function getTimeline(){
        var id = $('input[name="id"]').val();
        twtrUtil.getTimeline(handleResponse,id);
    }

Your next thought would be “how do I get a twitter timeline id?”. Its easy to do, just create a widget in your Twitter account, find the public timeline that you want to use, then create the Widget. Once created the Widget ID appears in the URL of the widget create success page. The ID identifies the widget which of course is setup to show the timeline that you selected.

See this example URL which illustrates where to find the ID:

  • https://twitter.com/settings/widgets/646067303877115905/edit?focus_textarea=1&notice=WIDGET_CREATED