How to load Facebook Pixel NoScript code in DNN codebehind?

浪尽此生 提交于 2019-12-02 17:05:39

问题


We have a checkout module with custom code which will show a wizard for End Users and another multi view when the user is a Dealer. I am trying to only fire the Facebook pixel code when the user is an End User. The problem I am having is the NoScript code which I can't call in a JavaScript function. I also don't want to put it after the script tags in the ASCX file because the rest of the pixel code is only called when an invoice is generated and the Facebook Pixel Helper Browser Extension is giving an error because of this. I attempted to split the Script and NoScript code. In the codebehind below I am setting the Facebook Pixel ID from a module setting which I have set. I have also created a setting for the NoScript code which is the FacebookPixelForEndUserNoScriptImageCode setting.

if (Settings["FacebookPixelIDForEndUser"] != null && !string.IsNullOrWhiteSpace(Settings["FacebookPixelIDForEndUser"].ToString())){
      EndUserFirstName = SessionManager.CurrentUserInfo.FirstName;
      EndUserLastName = SessionManager.CurrentUserInfo.LastName;
      EndUserEmail = SessionManager.CurrentUserInfo.PersonalEmailAddress;

      facebookInitializationCodeID = Settings["FacebookPixelIDForEndUser"].ToString();
      ScriptManager.RegisterStartupScript(Page, this.GetType(), "attacheEvents", "javascript:initializeFacebookPixelCodeForEndUser();", true);

      string FacebookPixelNoScriptCode = Settings["FacebookPixelForEndUserNoScriptImageCode"].ToString();
      Page.ClientScript.RegisterStartupScript(this.GetType(), "FacebookPixelForEndUserNoScriptImageCode", FacebookPixelNoScriptCode, false);
}

The code below is the front end code which is called from the codebehind.

    function initializeFacebookPixelCodeForEndUser(){
    var custemail = '<%=EndUserEmail%>';
    var custfirstname = '<%=EndUserFirstName%>';
    var custlastname = '<%=EndUserLastName%>';

    !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', '<%=facebookInitializationCodeID%>', {
        em: custemail,
        fn: custfirstname,
        ln: custlastname,
    });
    fbq('track', 'PageView');
}

This is the NoScript code which I set in the settings and call right after the RegisterStartupScript code has been called.

<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr? 
id=RemovedTheIDForPrivacy&ev=PageView&noscript=1"
/></noscript>

My current code seems to be failing as it is saying that fbq is undefined. I am calling the Purchase Event right after the above code has been called, but I think it is failing because the code is not together.

<script>
 fbq('track', 'Purchase', {
   value: 1,
   currency: 'ZAR',
 });
</script>

Are there any solution on how to call the Script and NoScript code within Javascript / JQuery?


回答1:


Typically when you have an error about fbq not initialized it is due to the code that you are rendering triggering before the actual Facebook script is called, thus it is not defined yet.

I would ensure that the reference to the Facebook JS is before your code (for example at the top of the skin, or header, rather than the footer.)

As for the no script, if you want to load it from the code behind you can use an <asp:literal> control to render it to the page if you are using the WebForms pattern.




回答2:


I managed to solve this problem by writing the Facebook Pixel Tracking code on the server-side using StringWriter.

if (!SessionManager.CurrentUserInfo.IsCustomerDealer)
                {     

                    if (Settings["FacebookPixelIDForEndUser"] != null && !string.IsNullOrWhiteSpace(Settings["FacebookPixelIDForEndUser"].ToString()))
                    {
                        EndUserFirstName = SessionManager.CurrentUserInfo.FirstName;
                        EndUserLastName = SessionManager.CurrentUserInfo.LastName;
                        EndUserEmail = SessionManager.CurrentUserInfo.UserName;

                        facebookInitializationCodeID = Settings["FacebookPixelIDForEndUser"].ToString();

                        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);

                    }
                }


来源:https://stackoverflow.com/questions/49654538/how-to-load-facebook-pixel-noscript-code-in-dnn-codebehind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!