4

if one calls the facebook function:

fbq('init', <pixel_id>)

more than once for the same pixel id, it generates the error:

Facebook Pixel Error: Duplicate Pixel ID

the solution on this answer is to use first

if(typeof fbq === 'undefined') {
fbq('init', <pixel_id>)
}

however i am using multiple pixel_ids on the same page. so this will not load the second pixel id if the first is already loaded.

is there a way to check if a particular pixelid is loaded and not just if fbq is loaded? something like:

if(typeof fbq === 'undefined') {
    fbq('init', <pixel_id>);
}
else {
    if (!fbq.pixel_id)
            fbq('init', <pixel_id>);
}
Community
  • 1
  • 1
michael
  • 308
  • 3
  • 18

1 Answers1

5

You should be able to use

fbq.getState().pixels[0] 

to identify which pixel is already loaded.

You then simply need to call the init function again, but with the new pixel id

fbq('init', <pixel_id>);

You should then be able to see that you have 2 pixels loaded

fbq.getState().pixels.length

In summary, to modify your initial code, i believe what you want is:

if(typeof fbq === 'undefined') {
    fbq('init', <pixel_id1>);
}
else {
    if (fbq.getState().pixels[0] === <pixel_id2>)
            fbq('init', <pixel_id2>);
}

And so forth - You can loop the whole collection of pixels in the pixels array to avoid double posting any of them.

You can even use this API to check how many events any pixel has fired (though not which events it has fired) via

fbq.getState().pixels[0].eventCount

That may be helpful in case you want to ensure that you only fire an event once, by checking that the count is zero.

When you subsequently decide to track an event, this will be fired for all pixels.

To verify this send, something like the following

fbq('track', 'PageView');

And check that the eventCount for both pixels has been incremented. You should be able to see the http requests for both pixels being fired too (via the Network tab on Chrome Developer Tools)

Anastasiosyal
  • 6,494
  • 6
  • 34
  • 40
  • 1
    The intend is good, but the code sample sufferes from race-condition where fbq is not undefined but 'getState' is. This can happen, if FB started to load, but did not finish. – Patrik Beck Aug 20 '18 at 10:50