Facebook Like Box social plugin doesn't work w

2020-04-08 12:42发布

问题:

I'm using the Like Box social plugin (https://developers.facebook.com/docs/reference/plugins/like-box/) and it works great.

Problem is that I'm using it within a Rails 4 application with Turbolinks. Whenever I reload a page, the like box shows up. If I click on any link, the next page loads and the Like Box doesn't show up.

I tried this already but didn't worked =/

http://reed.github.io/turbolinks-compatibility/facebook.html

Any ideas on how to solve this problem?

回答1:

The link you have posted in original question is quite nice. It asks us to create three functions:

1) saveFacebookRoot: This is needed so that the div#fb-root can be restored at a later point. This is called upon page:fetch. page:fetch is called while the DoM is still of the old page. i.e: new page has not replaced the old page

2) restoreFacebookRoot: This is needed to that the div#fb-root can be appended back to the page. It is called on page:change. page:change is called when the new DoM is available.

3) There is minor typo in there. We need to call this in page:load

FB.XFBML.parse() // Correct

Instead of :

FB?.XFBML.parse() // InCorrect

Remember that when the page is first reloaded, only the page:change is called out of these three.

The trick here is the use of global variables fb_root and fb_events_bound. These must be accessible in all other pages, but this is the reason why we hate turbolinks in the first place.

References: http://reed.github.io/turbolinks-compatibility/facebook.html



回答2:

Install observejs:

gem 'observejs'

Then add tag to the widget:

<div as="FB" class="fb-comments" data-href="<%= request.original_url %>"></div>

Then create a new script in javascripts folder (fb.coffee in my example):

ObserveJS.bind 'FB', class
  root: document.createElement('div')
  @::root.id = 'fb-root'

  loaded: =>
    if !document.body.contains(@root)
      document.body.appendChild(@root)

    if FB?
      FB.XFBML.parse()
    else
      @initialize()

  initialize: =>
    js = document.createElement('script')

    script = document.getElementsByTagName('script')[0]
    js = document.createElement('script')
    js.id = 'facebook-jssdk'
    js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID&version=VERSION_OF_API"
    script.parentNode.insertBefore(js, script)

Include the js files in your application.js

//= require observejs
//= require fb