javascriptreactjsfacebook-pixel

Do not trigger pixel if url contain word page


Facebook pixel triggering two times as because there are two urls in the same page [ redirection ]. but i want facebook pixel to trigger only one time.

I tried the below code :

var add = window.location.toString();

  if (add.indexOf("page=") != -1) {

        fbq('track', "PageView");
    }

So that if there is text "page" in url, then facebook event "PageView" should not trigger.

enter image description here

but if i use above code, not even a single facebook pixel will trigger. am i using wrong code ?

below is entire code i am using :

<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', '908483260167518');
  //fbq('track', 'PageView');
  $(function() {
    if ( document.location.href.indexOf('page') > -1 ) {
      fbq('track', "PageView");
    }
  /*
  var add = window.location.toString();
  if (add.indexOf("page=") != -1) {
        fbq('track', "PageView");
    }
    */
    
});

I also tried this :

var url = window.location.href;

if (url.search("#Work") >= 0) {

    fbq('track', 'PageView');
}

Solution

  • your problem may be the asynchronous loading of jQuery. You don't need jQuery for a simple URL check.

    remove your jQuery

    // $(function() {
    //    if ( document.location.href.indexOf('page') > -1 ) {
    //      fbq('track', "PageView");
    //    }
    // }); 
    

    and instead do the check in pure JavaScript

    // Directly after fbq('init', 'YOUR_PIXEL_ID');
    if (window.location.href.indexOf('page=') > -1) {
      fbq('track', 'PageView');
    }