Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
JavaScript

Get Tweets with Twitter API Javascript

2022-07-20

Due to change in twitter API, its been hard to get tweets from twitter to your site using javascript. We got new API version 1.1 and the old version 1 is not working any more, so we have to live with what ever 1.1 offers. This version of API supports widgets to keep in our sites, but thats not enough if we want to customize tweets using javascript to fit our sites look and functionality. We want json of the tweets, then we can do what ever we want with those. Its simple as creating a widget in twitter and then we get tweets from it to form json.

  1. Go to www.twitter.com and sign in then go to your settings page.
  2. Go to "Widgets" on the left hand side.
  3. Create a new widget as you like.
  4. Check "exclude replies" if you dont want replies in results.
  5. Now go back to settings -> widgets page, you will see the widget you just created. Click edit.
  6. Now look at the URL in your web browser, you will see a long number like this: 441110970094473216.
  7. Use this as your ID below!
var tw = function () {
  return {
    fetch: function (twid, tc, cbf) {
    (tweets_count=tc, cbfunc = cbf, c = document.createElement("script"), c.type = "text/javascript", c.src = "//cdn.syndication.twimg.com/widgets/timelines/" + twid + "?&lang=en&callback=tw.callback&suppress_response_codes=true&rnd=" + Math.random(), document.getElementsByTagName("head")[0].appendChild(c))
    },
    callback: function (e) {
      var c = document.createElement("div");
      c.setAttribute("id", "twitter-stage");
      c.innerHTML = e.body;
      c.style.display="none";
      document.body.appendChild(c);
      var tweet_json = [];
      usr_imgs = document.querySelectorAll('#twitter-stage div ol.h-feed li div.header div a.u-url.profile img.u-photo.avatar');
      usr_names = document.querySelectorAll('#twitter-stage ol li div.header span.full-name span');
      usr_screen_names = document.querySelectorAll('#twitter-stage ol li div.header a.u-url.profile span b');
      tweets = document.querySelectorAll('#twitter-stage ol li div.e-entry-content p.e-entry-title');
      dates = document.querySelectorAll('#twitter-stage ol.h-feed li div.header a time');
      tweetids = document.querySelectorAll('#twitter-stage ol.h-feed li div ul li:first-of-type a');
      for(i=0;i
Now include the file and use it as following
function tweets(tws){
  $.each(tws, function(i,o){
    // You can do as you wish with the values in 'o' objects.
    console.log(o);
  });
}
// this will fetch tweets of the given widget id and pass the tweets to tweets function
tw.fetch('441110970094473216', 20, tweets);

This is much straight forward approach, you can extend it as you like.