Advanced - Facebook Pixel

文章推薦指數: 80 %
投票人數:10人
Pixelsinstalledusingantagalsosupportparameters,whichyoucanincludeinyourquerystring.Forexample: Limitations Cannotbefiredmultipletimesoneachpageload CannottrackstandardorcustomeventstriggeredbyUIinteractions(e.g.,abuttonclick) SubjecttoHTTPGETlimitsinsendingcustomdataorlongURLs Cannotbeloadedasynchronously ExampleIMGtaginstallation BelowisanexampleofFacebookPixelIMGtaginstallationacrosskeypagesofafictitiouswebsiteusingafictitiouspixelID(12345)andcustomparameters(e.g.cd[currency]=USD). Ontheproductpage,apixeltotrackaPageVieweventandanothertotrackaViewContentevent: Ontheadd-to-cartpage,onepixeltotrackaPageVieweventandanothertotrackanAddToCardevent,withcustomdata: Onthepurchasepage,onepixeltotrackaPageVieweventandanothertotrackaPurchaseevent,withdataaboutthepurchase: AggregatedEventMeasurementIMGPixelforiOS14.5+ WiththeenforcementofApple'sAppTrackingTransparency(ATT)promptapproaching,FacebookislaunchingAggregatedEventMeasurement(AEM)tohelpyoumeasurecampaignperformanceinawaythatisconsistentwiththetrackingchoicesiOS14.5+usersmakewhenweshowthemtheATTprmptintheFacebookapp.WhenauseroptsoutonFacebook,AEMallowsyoutostillreceivede-identified,aggregatedeventinformationabouteventstakingplaceonyourapp. WestronglyrecommendfollowingtheInstallthePixelusinganIMGtagsectionofthisdocwhenusingthepixelIMGtagortoforgousingtheIMGtagandfollowourImplementationguideinstead. MissingIMGPixelData RuntimeJavascript IfyousetupyourIMGpixelbyusingruntimeJavaScripttogenerateaJavaScriptImageclasswithoutappendingthatImageclassontothewebsite'sDOMtree,forexample,usingthirdpartyJavaScriptlibrariestosendyourIMGpixel,youmustaddthefollowingcodeorFacebookwillnotreceiveyourIMGpixeldata. varnativeBridge=window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.receiveImgPixel; if(nativeBridge){ constpostObj={ id:{pixel-id}, ev:{standard-event}, cd:{stringified-custom-data}, dpo:{data-processing-options},//OptionalCCPAparam dpoco:{data-processing-option-country},//OptionalCCPAparam dpost:{data-processing-option-state},//OptionalCCPAparam }; nativeBridge.postMessage(JSON.stringify(postObj)); }SandboxAttribute IfyouplaceyourpixelIMGwithinaniframethathasthesandboxattributeyoumustaddtheallow-scriptsvalueorFacebookwillnotreceiveyourIMGpixeldata. TrackingclicksonButtons Supposeyouhaveane-commercewebsiteandyour"AddtoCart"buttondoesnotnavigatetoanewpage.Youmaywanttoactivateaneventwhenthebuttonisclicked. Inthisexample,wewillactivateaViewContentstandardeventonpageload.Whensomeoneclicks"AddtoCart"button,wewillactivateanAddToCartstandardevent. Todothis,firstloadFacebookPixelcodethatyouwanttofireonpageload: ThenfireAddToCarteitheronanewpageloadorontheclickofanAddToCartbutton.Therearemultiplewaystohandleclicksonbuttons.Here'sanexampleaddinganeventListenertoabutton. AddToCart varbutton=document.getElementById('addToCartButton'); button.addEventListener( 'click', function(){ fbq('track','AddToCart',{ content_name:'ReallyFastRunningShoes', content_category:'Apparel&Accessories>Shoes', content_ids:['1234'], content_type:'product', value:4.99, currency:'USD' }); }, false ); Therearemanywaysyoucanhandleclickevents;justmakesuretoalwayscallfbqfunctionaftertheclick. Dependingonhowyouhaveimplementedthepixel,thePixelHelpermayshowanerrorbeforethebuttonisclicked.Youcanverifythatyourpixelisfiringcorrectlybyclickingthebutton,whichdismissesthehelper'serror. Triggeringeventsbasedonvisibility Forthisexample,supposeyouhaveablogandwanttotrackuserswhoreadtheentirecontentofanarticle.There'snoactionfromtheuserotherthanscrollingtotheendofthepage. Here'sthesampleHTMLforapagewherethepixelloads:

ScrollPageuntiltheLeadeventisfired

Leadeventwillfirewhenthisphraseentersthescreen Whentheh1elementwithid=fb-fire-pixelappears,weshouldfiretheLeadstandardevent.Toverifyanelementisvisibleonscreen,weaddthefollowingcodetothepage: //ThiscodeshouldbeloadedtogetherwithFacebookPixel varexecuteWhenElementIsVisible=function(dom_element,callback){ if(!(dom_elementinstanceofHTMLElement)){ console.error('dom_elementmustbeavalidHTMLElement'); } if(typeofcallback!=='function'){ console.error( 'Secondparametermustbeafunction,got', typeofcallback, 'instead', ); } functionisOnViewport(elem){ varrect=elem.getBoundingClientRect(); vardocElem=document.documentElement; return( rect.top>=0&& rect.left>=0&& rect.bottom<=(window.innerHeight||docElem.clientHeight)&& rect.right<=(window.innerWidth||docElem.clientWidth) ); } varexecuteCallback=(function(){ varwasExecuted=false; returnfunction(){ if(!wasExecuted&&isOnViewport(dom_element)){ wasExecuted=true; callback(); } }; })(); window.addEventListener('scroll',executeCallback,false); };Afterthat,weneedtodefinehowtofirethepixelwhentheelementisvisibleonscreen: //Gettheelementthatshouldbevisibletotriggerthepixelfire varelement=document.getElementById('fb-fire-pixel'); //Then,settheeventtobetrackedwhenelementisvisible //Notethatsecondparameterisafunction,notafunctioncall executeWhenElementIsVisible(element,function(){ fbq('track','Lead'); });Triggeringeventsbasedonpagelengthorpercentage Forthisexample,supposeyouwanttotrackuserswhoreaduptoalengthorpercentageofthepage.There'snoactionfromtheuserotherthanscrollingtothedesiredpagelengthorpercentage. Thisfirstexampleistotrackthelengthofthepagewhichtheuserhasread.Intheexample,wearefiringofftheleadpixelwhenuserhasreadupto500pxlengthofthepage. varexecuteWhenReachedPageLength=function(length,callback){ if(typeoflength!=='number'){ console.error( 'Firstparametermustbeanumber,got', typeoflength, 'instead', ); } if(typeofcallback!=='function'){ console.error( 'Secondparametermustbeafunction,got', typeofcallback, 'instead', ); } functiongetWindowLength(){ returnwindow.innerHeight|| (document.documentElement||document.body).clientHeight; } functiongetCurrentScrolledLengthPosition(){ returnwindow.pageYOffset|| (document.documentElement||document.body.parentNode||document.body).scrollTop; } varexecuteCallback=(function(){ varwasExecuted=false; returnfunction(){ if(!wasExecuted&&getCurrentScrolledLengthPosition()>length){ wasExecuted=true; callback(); } }; })(); if(getWindowLength()>=length){ callback(); }else{ window.addEventListener('scroll',executeCallback,false); } }; executeWhenReachedPageLength(10,function(){ fbq('track','Lead'); });Thissecondexampleistotrackthepercentageofthepagewhichtheuserhasread.Intheexample,wearefiringofftheleadpixelwhenuserhasread75%ofthepage. varexecuteWhenReachedPagePercentage=function(percentage,callback){ if(typeofpercentage!=='number'){ console.error( 'Firstparametermustbeanumber,got', typeofpercentage, 'instead', ); } if(typeofcallback!=='function'){ console.error( 'Secondparametermustbeafunction,got', typeofcallback, 'instead', ); } functiongetDocumentLength(){ varD=document; returnMath.max( D.body.scrollHeight,D.documentElement.scrollHeight, D.body.offsetHeight,D.documentElement.offsetHeight, D.body.clientHeight,D.documentElement.clientHeight ) } functiongetWindowLength(){ returnwindow.innerHeight|| (document.documentElement||document.body).clientHeight; } functiongetScrollableLength(){ if(getDocumentLength()>getWindowLength()){ returngetDocumentLength()-getWindowLength(); }else{ return0; } } varscrollableLength=getScrollableLength(); window.addEventListener("resize",function(){ scrollableLength=getScrollableLength(); },false) functiongetCurrentScrolledLengthPosition(){ returnwindow.pageYOffset|| (document.documentElement||document.body.parentNode||document.body).scrollTop; } functiongetPercentageScrolled(){ if(scrollableLength==0){ return100; }else{ returngetCurrentScrolledLengthPosition()/scrollableLength*100; } } varexecuteCallback=(function(){ varwasExecuted=false; returnfunction(){ if(!wasExecuted&&getPercentageScrolled()>percentage){ wasExecuted=true; callback(); } }; })(); if(getDocumentLength()==0|| (getWindowLength()/getDocumentLength()*100>=percentage)){ callback(); }else{ window.addEventListener('scroll',executeCallback,false); } }; executeWhenReachedPagePercentage(75,function(){ fbq('track','Lead'); });DelayedPixelFires Supposeyouwanttotrackuserswhointeractwithyourwebsiteafewsecondsbeforefiringapixelevent.YoucandothiswiththesetTimeoutfunction. //Delaypixelfireby3seconds varseconds=3; setTimeout(function(){ fbq('track','Lead'); },seconds*1000);Itcouldbeusedtotrack“engaged”visitstoapage,wherepeoplearenotbouncingtoofastandareactuallyreadingthecontent. Triggeringeventsbasedonarticlesviewedpersession Ifyouwanttoknowwhoviewedacertainnumberofarticlesfromyoursite,youcanhaveasessioncounterandloadFacebookpixelcodewhenthisoccurs. Weknowthatasessionisagroupofuserinteractionswithyourwebsitethatcantakeplacewithinagiventimeframepersiterequest.Youcanincreasethenumberofpageviewsaslongasyoudetectuseractivitiesgiveatimeframe. AssumeyouhavethevariablesessionCountViewspersite_request,youcanaddtheFacebookpixelcodebasedonthenumberofpageviewsyoucounted. Examplecountingonlyforthe6tharticleviewed if(site_request.sessionCountViews==6){ fbq('track',"ViewContent",{ sessionCountViews:site_request.sessionCountViews, }); }Selectiveeventtrackingwithmultiplepixels Ifyouhavemultiplepixelsonthesamepageandwouldliketoselectivelyfireeventsoneachuniquepixel,thetrackSingleandtrackSingleCustomcapabilitiesshouldbeused. Usingthetrackfunctiononpagesthathavemultiplepixelsinitialized(eitherusingmultiplebasecodesorevencombiningitwithinonebasecode)couldproduceover-firingorunexpectedbehaviourandshouldbeappliedonlyinspecificsituations. ExamplewherewefireaPageVieweventonbothinitializedpixelsandselectivelyfireaStandardevent(Purchase)ononepixelandaCustomEventonasecondpixel. fbq('init',''); fbq('init',''); fbq('track','PageView');//firePageViewforbothinitializedpixels //onlyfirethePurchaseeventforPixelA fbq('trackSingle','','Purchase',{ value:4, currency:'GBP', }); //onlyfirethecustomeventStep4forPixelB fbq('trackSingleCustom','','Step4',{ //optionalparameters });Trackingeventsforindividualpixels Inunusualcases,youmaywanttosendeventstojustoneofthepixelsinstalledonyourwebsite;forexample,torestrictthedatasenttooneofthepixelsonyourwebsite. Thesemethodstrackpixelfiresforasinglepixel.They'recalledusingthefollowing: fbq('trackSingle','FB_PIXEL_ID','Purchase',customData); fbq('trackSingleCustom','FB_PIXEL_ID','CustomEvent',customData);AutomaticConfiguration TheFacebookpixelwillsendbuttonclickandpagemetadata(suchasdatastructuredaccordingtoOpengraphorSchema.orgformats)fromyourwebsitetoimproveyouradsdeliveryandmeasurementandautomateyourpixelsetup.ToconfiguretheFacebookPixeltonotsendthisadditionalinformation,intheFacebookPixelBasecode,addfbq('set','autoConfig','false','FB_PIXEL_ID')abovetheinitcall. ContentSecurityPolicy IfyourwebsitehasaContentSecurityPolicy,youshouldallowJavaScripttoloadfromhttps://connect.facebook.net.Note:Thepixelloadscriptsfromtwopaths:/en_US/fbevents.jsand/signals/config/{pixelID}?v={version}.


請為這篇文章評分?