Embedding a Tweet in a CMS that Blocks JavaScript

I recently wanted to let my CMS users easily embed tweets into their blog posts. There were the following problems / requirements:

  1. Our CMS doesn't allow users to post scripts, so Twitter's embed code was out of the question.
  2. Some of our users have zero HTML experience, so even using Twitter embed code without the script (and just globally including the twitter widget code) wasn't an option.
  3. I wanted it to be as easy as possible, with little room for error. So solutions like "Go get the ID of the tweet and do XYZ..." wasn't an option either.

I ended up using a two-part solution:

  1. Ask CMS users to embed tweets by using the "Copy Link to Tweet" option to get the URL of the tweet and pasting this in the CMS as a regular anchor tag. Our CMS has a link toolbar so this is a simple copy/paste for them.
  2. Include a script in my CMS site template that will find these links and convert them into embedded tweets.

After a CMS user included a tweet link, their post ended up with a link like this:

<a href="https://twitter.com/MikeSmithDev/status/517369050079326209">View Tweet</a>

The text of the hyperlink doesn't really matter since it is going to be replaced anyway. If the script successfully retrieves the HTML for the embedded version of the tweet it will add that HTML into the article and remove the original hyperlink.

Below is the JavaScript that turns any tweet link into an embedded tweet. I put this at the footer of the template page that hosts all our CMS pages.

You can download an example at https://github.com/MikeSmithDev/TweetLinkToEmbedded

<script>
//loop through all anchor tags that are within the element containing the CMS post
$('a', $('#CMSContainer')).each(function () {
    var link = this;
    var url = $(link).attr('href');
    var tweetId = url.substring(url.lastIndexOf("/") + 1);
    //see if the href fits the criteria of being a tweet url
    if (url.indexOf('https://twitter.com') === 0 && url.indexOf('status') > 0 && !isNaN(tweetId)) {
        $.ajax({
            url: 'https://api.twitter.com/1/statuses/oembed.json?id=' + tweetId,
            crossDomain: true,
            dataType: 'jsonp'
        })
        .done(function (data) {
            //insert tweet embed html (data.html) & remove original link.
            $(link).after(data.html).remove();
        });
     };
 });
 </script>

Happy coding!