javascriptfacebook-pixel

FB pixel. Get client id (fbp)


We wanna push data in FB Pixel like in Google Analytics.
By this link https://www.facebook.com/tr?id=&ev=test_event I can push data in Pixel but it will just event, for link this event and client, need client_id (in pixel it's call fbp, if I don't make mistake).

What we want to do in general:
JS have to get pixel client_id, then send by ajax to our server, server will make some analyze, then send data to FB pixel.
So, I have to get pixel client_id on JS.
For example, in GA you can get client_id by this code: ga.getAll()[0].get('clientId');

Example, send to Pixel by JS

fbq('track', 'AddToCart', {
    content_name: 'Really Fast Running Shoes', 
    content_category: 'Apparel & Accessories > Shoes',
    content_ids: ['1234'],
    content_type: 'product',
    value: 4.99,
    currency: 'USD' 
});

in "Network" I see, that send
https://www.facebook.com/tr/?id=pixel_id&ev=AddToCart&dl=https%3A%2F%2Flusido.000webhostapp.com%2Ffor_test%2FFB_pixel%2F&rl=&if=false&ts=1568822256426&cd[content_name]=Really%20Fast%20Running%20Shoes&cd[content_category]=Apparel%20%26%20Accessories%20%3E%20Shoes&cd[content_ids]=%5B%221234%22%5D&cd[content_type]=product&cd[value]=4.99&cd[currency]=USD&sw=1920&sh=1080&v=2.9.4&r=stable&ec=3&o=30&fbp=fb.1.1568641299934.291266893&it=1568732325055&coo=false&rqm=GET
...&fbp=fb.1.1568641299934.291266893... request already have fbp.

So, question: How can I get pixel client_id?


Solution

  • function getFbClientId() {
      let result = /_fbp=(fb\.1\.\d+\.\d+)/.exec(window.document.cookie);
      if (!(result && result[1])) {
        return null;
      }
      return result[1];
    }
    getFbClientId();