Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Facebook Pixel to Vue project

I am trying to implement Facebook pixel in a Vue project, but I can't seem to figure out where to implement it. I created a .js file with the fb code. I think I am supposed to be calling it in vue.config.js (I saw that in an example where the user also used Nuxt (which I am not using). I added it like this script: { src: 'external.js', type: 'text/javascript' })

but it is not working and I really need some help.

like image 570
Saar94 Avatar asked Dec 24 '22 03:12

Saar94


1 Answers

This is how I implements it for my Vue/Angular/React projects.

Normally the FB pixel code consist of 2 part

  1. the initializing code

e.g.

<!-- Facebook Pixel Code -->
<script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', 'YOUR_APP_ID');
</script>
<noscript><img height="1" width="1" style="display:none"
  src="https://www.facebook.com/tr?id=YOUR_APP_ID&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
  1. the tracking function

like fbq('trackCustom', 'SOME_PAGE_NAME');

What works for me is to put the initializing code in the index.html in src.

And put the tracking function to where it should be. for e.g. if it's tracking signup, I put fbq('trackCustom', 'signup'); in the function after signup is successful.

Similar concepts can be applied to Google Analytics as well.

like image 193
Jacob Goh Avatar answered Jan 06 '23 05:01

Jacob Goh