Search code examples
c#jqueryfacebookpixel

Detect if a users Anti-Virus or Browser is blocking marketing tracking code like Facebook FBQ?


Is there a way you can detect in C# if a browser is blocking external marketing tracking information like fbq?

In JQuery you can use typeof fbq !== 'undefined' to detect if the Facebook Pixel tracking code is blocked, For example:

if(typeof fbq !== 'undefined'){
   fbq('track', 'ViewContent', {
    value: FacebookPriceIncVat,
    currency: FacebookInitiateCheckoutCurrency,
    content_ids: FacebookSKUView,
    content_type: 'product',
 });
}

I have one module in which the Facebook Tracking code can only be generated on the back-end. Is there a way you can detect if fbq exist using perhaps ajax that changes a bool or some other way to detect if something is blocking links in your browser like a plugin of some sort?

The code below should not execute if fbq is not present.

if (FacebookPixelID != null)
      {
        EndUserFirstName = SessionManager.CurrentUserInfo.FirstName;
        EndUserLastName = SessionManager.CurrentUserInfo.LastName;
        EndUserEmail = SessionManager.CurrentUserInfo.UserName;

        FacebookInitializationCodeID = FacebookPixelID;

        string FacebookPixelResult = string.Empty;

        using (var FBPxl = new StringWriter())
          using (var FBCodescript = new HtmlTextWriter(FBPxl))
          {
              FBCodescript.AddAttribute(Attr.Type, "text/javascript");
              FBCodescript.RenderBeginTag(Tag.Script);
              //load ecommerce plugin
              FBCodescript.WriteLine("!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)};");
              FBCodescript.WriteLine("if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0';");
               FBCodescript.WriteLine("n.queue =[]; t = b.createElement(e); t.async = !0;");
               FBCodescript.WriteLine("t.src = v; s = b.getElementsByTagName(e)[0];");
               FBCodescript.WriteLine("s.parentNode.insertBefore(t, s)}");
               FBCodescript.WriteLine("(window, document,'script','https://connect.facebook.net/en_US/fbevents.js');");
               FBCodescript.WriteLine($"fbq('init', '{FacebookInitializationCodeID}', {{ em: '{EndUserEmail}', fn: '{EndUserFirstName}', ln: '{EndUserLastName}',}});");
               FBCodescript.WriteLine("fbq('track', 'PageView');");
               FBCodescript.RenderEndTag();
               FBCodescript.WriteLine($"<noscript><img height='1' width='1' style='display:none'  src='https://www.facebook.com/tr?id={FacebookInitializationCodeID}&ev=PageView&noscript=1'/></noscript>");
               FacebookPixelResult = FBCodescript.InnerWriter.ToString();
          }

      Page.ClientScript.RegisterStartupScript(this.GetType(), "myFacebookPixelInitialization", FacebookPixelResult, false);

          //Facebook Pixels Purchase Code
          string FacebookPixelPurchase = string.Empty;

          if (RevenueCurrency != null)
          {
              FBPurchaseCurrency = RevenueCurrency;
          }
          else
          {
          FBPurchaseCurrency = "ZAR";
          }

          using (var FBPxlPurchase = new StringWriter())
          using (var FBCodescriptPurchase = new HtmlTextWriter(FBPxlPurchase))
          {
               FBCodescriptPurchase.AddAttribute(Attr.Type, "text/javascript");
               FBCodescriptPurchase.RenderBeginTag(Tag.Script);
               //Write Facebook Pixel Purchase Event code
               FBCodescriptPurchase.WriteLine("fbq('track', 'Purchase', {");
               FBCodescriptPurchase.WriteLine($"value: {trans.Revenue},");
               FBCodescriptPurchase.WriteLine($"currency: '{FBPurchaseCurrency}',");
               FBCodescriptPurchase.WriteLine($"content_ids: '{string.Join(",", trans.LineItems.Select(l => l.SKU).ToArray())}',");
               FBCodescriptPurchase.WriteLine("content_type: 'product',");
               FBCodescriptPurchase.WriteLine($"contents: [");
               var PurchaseCounter = 1;

              foreach (var lineitem in trans.LineItems)
                  {
                   FBCodescriptPurchase.WriteLine("{");
                   FBCodescriptPurchase.WriteLine($"id: '{lineitem.SKU}',");
                   FBCodescriptPurchase.WriteLine($"quantity: {lineitem.Quantity},");
                   FBCodescriptPurchase.WriteLine($"item_price: {lineitem.UnitPrice}");
                   FBCodescriptPurchase.WriteLine("}");
                   if (PurchaseCounter != trans.LineItems.Count) FBCodescriptPurchase.WriteLine(",");
                        PurchaseCounter++;
                   }
                      FBCodescriptPurchase.WriteLine("]");
                      FBCodescriptPurchase.WriteLine("});");
                      FBCodescriptPurchase.RenderEndTag();

                      FacebookPixelPurchase = FBCodescriptPurchase.InnerWriter.ToString();
                   }

       Page.ClientScript.RegisterStartupScript(this.GetType(), "myFacebookPixelPurchase", FacebookPixelPurchase, false);
                    }
             }  

Solution

  • I think it is actually easy to fix this. Don't know why I did not think of this.

    I can just add the if statement in the C# code.