Programmatically Clearing the Facebook Share Image Cache

When you share a URL on Facebook, it scrapes the page for the URL for the Open Graph data to determine what image/video to display.  Facebook caches the image for that URL, so if you change the image and then share the same URL at a later time, the old image will still get displayed, which is probably not what you want to do.

Facebook provides the Open Graph Debug Tool that can be used to manually clear the cached value for the URL, but that may not be a workable if your website allows images to be changed dynamically.  Ideally, you would want a way to programmatically clear the cache after the associated image is changed.

Fortunately, there is a way to clear the cache using the OpenGraph API by forcing a scrape of the URL. The key is to set the ‘scrape’ parameter to true in the API call. The following Ruby code assumes that the Facebook application id and secret are stored in environment variables.

facebook_open_graph.rb

module FacebookOpenGraph
  def self.clear_cache(url)
    params = {
      :client_id => ENV['FACEBOOK_APP_ID'],
      :client_secret => ENV['FACEBOOK_SECRET'],
      :grant_type => "client_credentials"
    }
    uri = URI("https://graph.facebook.com/oauth/access_token?#{params.to_query}")
    response = Net::HTTP.get(uri)
    access_token = Rack::Utils.parse_nested_query(response)["access_token"]
    unless access_token.nil?
      uri = URI('https://graph.facebook.com')
      res = Net::HTTP.post_form(uri, 'id' => "#{url}", 'scrape' => 'true',
          'access_token' => "#{access_token}", 'max' => '500')
    end
  end
end

Then to clear the cache you merely need to call the clear_cache method, passing in the URL being shared.

FacebookOpenGraph.clear_cache("http://myurl.com/some_cool_page")
Advertisements

8 thoughts on “Programmatically Clearing the Facebook Share Image Cache

    1. mdenomy Post author

      It’s Ruby, and I used it in a Rails project. You can do the same in other languages, just make the appropriate HTTP request. I’ll update the post to make that more clear, thanks.

      Reply
  1. Thomas

    Hey,
    That’s very useful, thank you for sharing!
    So, after placing this on initializers, may I ask you how you trigger it ? Since I assume that you use it on a “share” button. Just placing the line on the page will purge the facebook cache on load, but if the visitor doesn’t clic the “share” link, your og is purged. I’m wondering what happen to this point for previous shared thumbs & contents. Moreover, I think that fb will lock content after 50 purges.

    Reply
    1. mdenomy Post author

      Ah, let me provide a little background.

      I was using this on a crowdfunding app where people who created a fundraising campaign could upload photos to associate with the campaign. The photos were uploaded through our site and stored on Rackspace. People who contributed to the campaign could post on FB, and the banner photo would show up on their wall. If the “owner” of the campaign wanted to upload a new photo via our site, FB would not see the picture as having changed and would use a cached version, which is not the behavior we wanted. So we triggered the purge when a new banner photo was uploaded, which was more on an administrator operation, as opposed to a user “like” or “share” action.

      Previous likes/shares would show the updated image, which is what we wanted. I think you are right that FB will lock content after a certain amount of purges in a given time period, but we never got close to that. Usually a campaign owner only needed to make a few tweaks to the image or provide updates to keep it fresh.

      Hope that helps.

      Reply
  2. Thomas

    Hey, thank you very much for this detailled eplanation.
    That’s a smart move to call the purge on upload, I will definitely proceed this way.
    I tried to purge but with no success for now, since I have very few knowledge on facebook API. However, I’m wondering if facebook didn’t change it’s procedure (providing the debugger tool url).
    I’ve made a stackoverflow post for my issue (including a link to your post) resuming my tentatives.
    http://stackoverflow.com/questions/24376341/rails-4-facebook-clear-cache-for-sharing-button-link

    Reply
  3. kazim59

    Thanks, but I had to modify this to work.
    Here’s what works:

      def self.clear_cache(url)
        params = { 
          :client_id => Facebook::APP_ID,
          :client_secret => Facebook::SECRET,
          :grant_type => "client_credentials"
        }   
        uri = URI("https://graph.facebook.com/oauth/access_token?#{params.to_query}")
        https = Net::HTTP.new(uri.host, uri.port)
        https.use_ssl = true
        https.verify_mode = OpenSSL::SSL::VERIFY_NONE
        response = https.request_get(uri.path + "?" + uri.query)
        access_token = Rack::Utils.parse_nested_query(response.body)["access_token"]
        unless access_token.nil?
          uri = URI('https://graph.facebook.com')
          res = https.request_post('https://graph.facebook.com/?id=' + url + '&scrape=true&access_token=' + access_token, '') 
        end 
      end
    
    Reply
    1. mdenomy Post author

      Thanks for the update Kazim. It’s been a while since I first did this, so thanks for posting an update on how you got it to work.

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s