Force Facebook to pull latest page content in the share dialog

Posted 07/18/2014 by Debabrata Biswas

Facebook parses open graph tags like <og:title>, <og:image> as meta tags in the page, and uses these values in the share dialog. What I found was Facebook expects the image specified in <og:image> tag to be of the same width and height. If an image with equal height and width is not specified,Facebook will use a random image form the page for the thumbnail of the share dialog.

Once you share a page (like http://www.facebook.com/sharer/sharer.php?u=[my page url]) with the open graph meta tags, Facebook caches its content for a few days. So suppose you have filled the open graph meta tags using your Sitecore context item's fields like "Title", "Subtitle, "Dec", "Image" and then you change one of these, publish the item and expect these to be reflected on the Facebook share dialog immediately, you would be disappointed like me. Of course there are these two ways of clearing the FB cache:


(a)- go to "https://developers.facebook.com/tools/debug", enter the page url and click on "debug". 
(b)- Go to "https://www.facebook.com/sharer/sharer.php", enter the page url and click on "share".

It is not practical to expect end users to perform these steps each time an item is changed. I tried many possible solutions like one that talked about appending "v=1" (any numeric in fact) as a query string to the share page url. But I found this to be not 100% accurate. Fortunately I was able to find a solution to this and was able to clear the cache programmatically. Please find the code below. It uses Facebook API javascript function and calls FB scrapper/parser to forcefully parse the page for open graph meta tags. I call this function right after I fill the meta tags from code behind. In my example I pass the same placeholder that I used to fill in the meta tags. "GetUrl" is the function that returns the complete url of the page (as passed in value of query string "u" in the share url above) that contains my FB share button (and these open graph meta tags).


        private void ForceFBUpdate(SC.Web.UI.WebControls.Placeholder mPH)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<script src=\"http://code.jquery.com/jquery-latest.min.js\"; type=\"text/javascript\"></script>");
            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("$(document).ready(function(){");
            sb.AppendLine("$.post( 'https://graph.facebook.com',");
            sb.AppendLine("{");
            sb.AppendLine(string.Format("id:'{0}',", GetUrl()));
            sb.AppendLine("scrape: true");
            sb.AppendLine("}");
            sb.AppendLine(");");
            sb.AppendLine("}); </script>");
            Literal literal = new Literal();
            literal.Text = sb.ToString();

            mPH.Controls.Add(literal);
        }

Share:

Archive

Syndication