Georgi Atsev
Georgi Atsev

Reputation: 3045

Run facebook pixel with rails and turbolinks

The Facebook pixel's initialization code and PageView code is recommended to be placed inside the section: https://developers.facebook.com/docs/facebook-pixel/using-the-pixel#get

The problem is that the head of the webpage is never reloaded with Rails turbolinks. Pixel does send a pageView event to Facebook on pushState/popState, but with the wrong URL - the URL from the initial loading of the page. I'm assuming that pixel saves the initial location (when the fbq('init') is called) and then reuses it for the PageView event.

I tried to put the entire code segment in the body, but the result was "Facebook Pixel Error: Duplicate Pixel ID: XXXXXXXXXX" java script error.

I tried to split the code and put the fbq('init', XXXXX) event in the head and then on page:change event to call fbq('track', 'PageView'); But the problem is that this once again uses the initial URL.

I also tried to set the window.fbq variable to undefined and call again init before PageView - all of this in the page:change callback. But then I got the "Facebook Pixel Warning: Multiple pixels with conflicting versions were detected on this page" and again the PageView was called with the wrong url.

Has anyone ever made Facebook pixel work with turbolinks?

Upvotes: 4

Views: 1544

Answers (1)

Keith Layne
Keith Layne

Reputation: 3775

I'm using the following JS that gets loaded in the head:

/* insert pixel load function here */

function trackPageView() {
  fbq('init', 'PIXEL_ID')
  fbq('track', 'PageView')
}

document.addEventListener('turbolinks:load', trackPageView, true)

When I test it locally with the Facebook Pixel Helper it shows a PageView event on each page I navigate to with turbolinks, and no warnings.

Upvotes: 7

Related Questions