Advanced - Facebook Pixel
文章推薦指數: 80 %
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:
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}.
ScrollPageuntiltheLeadeventisfired
延伸文章資訊
- 1What is the difference between "PageView" and "ViewContent ...
What is the difference between "PageView" and "ViewContent" in Facebook pixel? ... View content i...
- 2參考資料- Facebook 像素
ViewContent 會告訴您是否有人造訪某個網頁的網址,但不會顯示他們在該頁面上觀看的內容或執行哪些動作。 有人到達產品詳細資料頁面。 content_ids 、 content_categ...
- 3facebook pixel: PageView vs. ViewContent - Stack Overflow
fbq('track', 'ViewContent', { content_name: 'Homepage' });. The PageView event just automatically...
- 4Zipify Pages: The "ViewContent" Facebook Pixel Event
This can have a negative effect on your FB ads retargeting efforts that use the ViewContent event...
- 5Facebook像素是什麼?可以做什麼用? - WACA
若商家正確填入代碼後,這些事件分別會出現在WACA網站的哪些地方呢? Pageview:瀏覽任何一頁. ViewContent:瀏覽各別商品頁. Add To Cart:點選網站中任 ...