If you’ve ever tried to use Facebook social plugins‘ latest version in your website, you might have noticed how smooth and streamlined is now the embedding process.
Select a button type, include the SDK, copy-paste a snippet of code and… you’re done! You can also leave the data-href attribute blank, so the plugin will like/share the current page. Awesome!
At this point you might ask yourself, “Well, will this nice little button work with my super cool AJAX-powered app?”. The answer is not really.
This is because the page metadata is parsed by Facebook SDK only when a full page load is triggered. So, if I navigate from example.com/page-one to example.com/page-two and try to click on my Facebook share button, it will prompt a share for /page-one.
updateFbButtonHref = (el) -> $fbButton = $(el).find('.fb-share-button') $fbButton.attr('data-href', window.location.href) FB.XFBML.parse()
Now, we can bind this function to the “page:load” event (in the case of a Turbolinks application), or generally after every pushState():
$(document).on 'page:load', -> updateFbButtonHref('.my-fb-button-container')
And we’re cool! Our button will now share the correct page.