Debug Guide For Web Analytics And Tag Management
文章推薦指數: 80 %
GA Debugger is the official Universal Analytics, Google Analytics 4, and Google Tag Manager debugger. It outputs information about the ...
SimoAhava
Husband|Father|Analyticsdevelopersimo(at)simoahava.com
Home
Categories
Tags
GTMTips
About
RSS
Tools
Blogstatistics
GitHub
Upcomingtalks
Templates
Newsletter
DebugGuideForWebAnalyticsAndTagManagement
January13,2022
in
Analytics
|Comments
Oneofthekeyskillsforanyoneworkingwithwebanalyticsandtagmanagementisunderstandinghowtoidentifywherethingswentwrong,whytheywentwrong,andideallyhowtofixthem.
Thereareplentyofexcellentbrowserextensionsforhelpingyoudebug,andwe’lldiscusstheseintheguide,too.Butmostofallwe’regoingtousebrowsers’owndevelopertools,astheyarealwaysthebestsourceoftruthforanythingthathappenswithinthebrowserwindow.
Intheguide,we’lluseGoogleAnalytics4andGoogleTagManagerasexamples.However,theguide’stopicscanbeextendedtoanywebanalyticstoolsandtagmanagementsolutionsoutthere,becausetheusecasesareuniversal.
X
TheSimmerNewsletter
SubscribetotheSimmernewslettertogetthelatestnewsandcontentfromSimoAhavaintoyouremailinbox!
Browserdevelopertools
Yourbestfriendindebuggingissueswithyourwebanalyticsandtagmanagementsystemsinthewebbrowserarethebrowsers’owndevelopertools.
Developertoolsareasuiteofutilitiesthatyoucanusetoinvestigatevariousdifferentaspectsofthedynamicwebpagetheuserisinspecting.
Theimageaboveliststhekeyboardshortcutsforopeningthedevelopertoolsinvariousbrowsersandoperatingsystems.
NotethatonSafari,you’llwanttoopenSafari->Preferences->AdvancedandcheckthebuttonnexttoShowDevelopmenuinmenubar.
AllofthebrowsersaboveutilizeasimilarsetofdevelopertoolswithjustsmalldifferencesintheUIandthechosensemantics.Themostusefultoolswe’llfocusonare:
Theelementinspector,whichletsyoulookatthedynamicrepresentationofthewebpage(DocumentObjectModel).ThisisparticularlyusefulforinspectinginjectedtrackingscriptsandcustomHTMLelementsaddedbytagmanagementsolutions.
Thenetworkdebugger,whichletsyouinspectandanalyzeoutgoingHTTPrequestssentfromthepage(orembeddedframes).Thisisoneofthemostimportanttoolsforyou,asitwilltellyouthetruthaboutwhatisactuallysentfromtheuser’sbrowser.
TheJavaScriptconsole,whichletsyourunJavaScriptcodeinthecontextofthecurrentpage(orembeddedframe).VitalforrecognizingissueswiththeJavaScriptimplementationsofyouranalyticsscripts.
Thesourcesbrowser,whichletsyoubrowsethroughtheJavaScriptresourcesloadedonthecurrentpage(orembeddedframes).GreatforidentifyingmismatchesbetweenwhatyouexpectedtheJavaScriptfiletocontainvs.what’sactuallycontainedwithin.
Theapplicationstorage,whichletsyouinvestigatethebrowserstorage(cookies,localStorage,etc.)utilizedonthecurrentpage(orembeddedframes).Instrumentalforunderstandingwhysometrackersmightnotbeabletopersistdataconsistently.
Inthissection,we’llwalkthroughthesedifferenttoolswithmoredetail,sothatyou’llhaveabetterunderstandingofhowtousethemtounravelsomeofthemorecomplicateddebuggingcasesyouruninto.
Note!ThissectionusesmainlyChrome’sdevelopertoolsinexamples.It’spossibletheactualactionsare(slightly)differentinotherbrowsers.
Elementinspector
TheelementinspectorletsyouanalyzetheDOM(DocumentObjectModel)ofthepage.
WhenthebrowserloadstheHTMLsourceitretrievesfromthesite’swebserver,itrendersitintoadynamictreemodel,accessibleviaJavaScript.ThisdynamicrepresentationistheDOM.
Wheneverananalyticssnippetoratagmanagerinteractswiththepage,suchasbyloadingathird-partyJavaScriptlibraryoraddingaclicklistenersomewhere,theymodifytheDOM.
Thus,ifyouhaveproblemswithyourimplementation,it’susefultosearchthroughtheelementinspectortofindwhattheissuecouldbe.
Theelementinspectorisalsoextremelyusefulwhenyou’rebuildingtriggersorvariablesinyourtagmanagementsystemwiththepurposeofscrapingsomeinformationfromthepageoraddinglistenerstoandinjectingelementsintothedocument.
Hereareacoupleofcooltricksyoucantryintheelementinspector.
Searchforaspecificelementintheinspector
HitCMD+F/CTRL+Ftoopenasearchbar.Youcanthensearchforastring(e.g.textcontent)oraCSSselectortohavetheinspectorlocateaspecificelement.
Forexample,tosearchforallelementswiththeclassnamesimmer,youcantype.simmerintothesearchbarandtheinspectorwillreturnallthematches.
Ifyou’reunsurewhetherGoogleTagManageractuallyaddedtheGoogleAnalytics4scriptonthepage,forexampled,youcouldsearchforgtag/jstofindallelementsthathavethatparticularstringsomewhereinthem.SinceGA4isloadedfromthe/gtag/js?id=G-...URL,theinspectorshouldfindtheGA4scriptelement,unlessit’sactuallymissing.
Selectaspecificelementonthepageitself
Youcanalsodothereverse.Ifyouclickthelittleelementselectoricon(thisdiffersfrombrowsertobrowser)inthedevelopertoolspanel,youcanactuallyselectanelementonthepagetorevealitintheelementinspector.
Inadditiontopinpointingitintheelementinspector,thetoolalsodisplayssomeusefulinformationabouttheelementinquestion.
Interactwiththeelementcontextmenu
Whenyouselectanelementintheinspectorwiththerightmousebutton,you’llseeacontextmenu.
Youcandoalotofcoolstuffwiththis,suchas:
Add/edittheelement’sattributes.IusethisalottochangelinkURLstosomethingelse,whenIwanttotestaspecificoutgoinglink,forexample.
Edit/deletetheelementitself.Sometimesit’susefultojustdeleteanelemententirely(e.g.anoverlaythathidesthepageunderneath).Andsometimesyou’llwanttoedittheentireHTMLstructureofanelementwhenyouwanttoaddnewcontentstoitfortestingaclicklistener,forexample.
Copyselector,asthisletsyoucopyaCSSselectorpathtotheelementitself.ExtremelyusefulwhenconfiguringtriggersinGoogleTagManager,forexample.JustnotethattheCSSselectorpathisusuallyneedlesslycomplex,andyoucantrimitdowntobemoregenericinordertoavoidsubtlechangesintheDOMfrombreakingyourtriggers.
Breakon…letsyoupausethepagewhenevertheelementoritssubtree(nestedelements)changes.Thisisprettyusefulwhenyouwanttoinspectwhathappenswhenanelementbecomesvisibleorwhenanelement’scontentisdynamicallychanged(thinkformvalidationerrormessages,forexample).
Changeelementstyles
Whenyou’veselectedtheelement,youcanchangetheassociatedstyleswiththedevelopertools.
Thismighthavemarginaluseforanalyticsdebugging,butoccasionallyyoumightuseittomakeanelementvisibleormoveitaroundwhenyoucan’tfinditintheactualpage.
Networkdebugger
Oftenyou’llfindthatyourtagmanagementsystemand/oryouranalyticsdebuggerextensionclaimsthatyourhithasfired,butnodataiscollectedintothevendorendpoint.
Atthispoint,youneedtoopentheNetworktabinthedevelopertools,asthislistsalltheHTTPrequestssentfromthebrowser.
Thenetworkdebuggeristheultimatetruth.Ifarequestdoesn’tappearhere,thenthebrowserhasnotsentit.SoifyourtagmanagementsystemsaysthataGA4hithasfiredbutyouseenoevidenceofacollect?v=2requestinthenetworkdebugger,thenthehithasnotbeensent.
ItmightbeusefultocheckthePreservelogoption,asthisdoesn’tclearthelogofrequestsbetweenpageloads.Thisisveryusefulwhenyouwanttodebugwhathappenedonapreviouspage.
Foramoredetailedwalkthroughofthenetworkdebugger,checkoutthisexcellentresource.
Herearesomeofthethingsyoucandowiththenetworkdebugger.
Filterforspecificrequests
Bytypingsomethingintothefilterfield,youcanshowonlytheHTTPrequeststhatmatchthefilter.
ThefiltersearchesthroughtherequestURLandtherequestbody.
Whenyouselectarequestinthedebugger,asmalloverlayopenswithvarioustabs.
HeadersincludesalltheHTTPheadersoftherequestandtheresponse.Thisisusefulfordebuggingthingslikecookies,referrervalues,andwheretherequestwasactuallysent.
Payloadcontainsthequeryparametersandtherequestbody.Extremelyimportantwhenanalyzingwhatwasactuallysenttotheanalyticsplatform.
Responseshowswhatthewebserveractuallyrespondedwith.Thisisoftenemptyornonsensicalwithpixelrequests,butit’susefulwhenanalyzingAPIresponsesorJavaScriptfiles.
Cookieslistsallthecookiesthatweresentwiththerequestandsetintheresponse.
Blockarequestfromfutureloads
Youcanright-clickanyrequestinthelistandchooseBlockrequestURLorBlockrequestdomaintopreventthepagefrombeingabletosendtherequestuntiltheblockisremoved.
WhentheresourceURL(ordomain)isblocked,thenanyrequeststhatmatchtheURL(ordomain)willbeblockedinfuturerequests.
ThisisextremelyusefulwhenyouwanttofigureoutwhichJavaScriptresourceiscausingconflictsonthepage.Byblockingeachone-by-oneandthenreloadingthepage,you’llbeabletopinpointthefilethatcausesissues.
Tounblockaresource,presstheESCkeytotoggletheDrawer,selecttheNetworkrequestblockingtabandunchecktheboxnexttotherequest(ordeleteitfromtherespectivebuttons).Ifyoudon’tseethetab,youcanselectitbyclickingtheDrawermenu(thethreeverticaldots)inthetop-leftcorneroftheDrawer.
Youcanalsoright-clicktheblockedresourceinthenetworkdebuggerandchooseUnblock….
Manuallythrottlethepagespeed
Ifyouwanttotesthowthepageloadslikeonaslowerconnection(mightbeusefuleverynowandthen),youcanchooseathrottlingspeedfromthenetworktools.
RemembertoswitchbacktoNothrottlingwhendone,though,oryou’llhavetocontinuesufferingwithslowlyloadingpages.
Pinpointtheinitiatoroftherequest
IntheInitiatorcolumn,youcanseetheresourceorprocessthatcausedtheredirecttofire.
Byclickingtheresourceinthecolumn,itwilljumptotherelevantpartofthedevelopertoolstoshowwhatprocessinitiatedtherequest.
Iftheinitiatoris(index),itmeanstherequestoriginatedfromaresourceinjectedintotheDOM,whichmeansclickingitwillopentheelementinspectorwiththeelementselected.
IftheinitiatorisaJavaScriptfileoraCSSfile,forexample,thendevelopertoolswillopentheSourcestabwiththerelevantpartofthesourcefilecodeselected.Thismightnotbeveryusefulinitself,butyoucanusetheSourcespaneltoaddabreakpointtotheinjectionmomentinordertoreplaythroughthestackafterapagereload(moreonthisbelowintheSourcessection).
JavaScriptconsole
TheJavaScriptconsoleletsyouexecuteanyJavaScriptcommandsinthecontextofthecurrentpage.
ThecontextofthepageistheDOM,andyoucanuseDOMmethodstointeractwithpageelements.
HerearesomeusecasesfortheJavaScriptconsole.
Inspectlogs
ManytoolsoutputdebugmessagestotheJavaScriptconsole,sothefirstcourseofactionwheneveryourunintotroubleistoopentheJavaScriptconsoletoseeifthereareanyrelevanterrorsshown.
It’sagoodideatoaddsomeconsole.log(msg)callsinwhatevercodeyouaddyourselfviaatagmanagementsystem,forexample.ThatwayyoucandebugthelogoutputintheJavaScriptconsole–oftenthisistheeasiestwaytodebugcodeexecution.
Checkthevalueofglobalvariables
InbrowserJavaScript,globalvariablesarestoredinthewindowobject.
IfyouwanttocheckwhetheraglobaldataLayerarrayexists,youcansimplytypewindow.dataLayerandpressenter.Iftheconsoleshowsundefined,itmeansthatdataLayerdoesnotexistinglobalscope.
Youcanalsosetnewglobalvariablessimplybyinitializingtheminthewindowobject:
window.myGlobalVariable="Hello,Iamaglobalvariable.";
Addaneventlistenerwithabreakpoint
Thisisacooltrick.WheneveranyJavaScriptthatrunsonthepageusesthedebugger;keyword,thepagewillpauseandyouwillbedivertedtotheSourcestabwhereyoucanthenwalkthroughthestack(moreonthisbelow).
Ifyouwanttotrythisout,youcanaddaclicklisteneronthepagewithdebugger;inthecallback.Then,whenyouclickanywhereonthepage,theexecutionwillpauseandyou’llbetakentotheSourcestab.
window.addEventListener('click',()=>{debugger;})
Changethecontexttoaniframe
TheJavaScriptconsoleisinitiallyboundtothecontextofthetopframe(theURLtheuseriscurrentlynavigating).
Ifthepageembedsothercontentiniframes,youcanusetheframeselectorintheconsoletochangecontexttotheiframe.
Thisis,ofcourse,particularlyusefulwhendebuggingembeddedcontentsuchasthird-partyshoppingcartsorwidgets.
Notethattheframeselectorisconfusinglyindifferentpartsofthedevelopertoolsacrossdifferentbrowsers.ThescreenshotaboveisfromChrome(andit’sthesameonEdge).WithFirefoxthecontextpickerisinthetop-rightcornerofthedevelopertools,andwithSafariit’sinthebottom-rightcornerofthedeveloperconsole.
Sources
Thesourcespanelcanbegame-changingbutitcanalsobeveryoverwhelmingtouse.
Thepanellistsallofthesubresources(images,scripts,frames,etc.)loadedonthecurrentpage.
ThelistissortedbyURL,startingwiththeoriginandthendrillingowntopathsandfiles.
Thesourcespanelwoulddeserveaseparatearticleinitselfduetothemany,manydifferentthingsyoucandowithit.However,hereI’velistedsomeofthemostusefulthingsyoucantamperwith.
Openafile,pretty-printit,andsearchthroughit
WhenyouopenaminifiedJavaScriptfile(astheytendtobeinordertosavespaceandbandwidth),thepanelpromptsyouifyouwanttopretty-printthefile.
Alwaysdothis.
Bypretty-printingthefile,thecodeisdisplayedinamorereadableformat,evenifthecodeitselfisstillminified.
YoucanthenhitCMD+F(orCTRL+F)toopenthesearchbar.Thesearchwilllookthroughtheformattedfileforallreferencestothesearchedstring.
Addabreakpointtothefile
Abreakpointisaninstructionforthebrowertohaltpageexecutionandallowtheusertoseetheexactstateofthepageatthetimeofthebreakpoint.
Toaddabreakpoint,openafileintheSourcespanel,right-clicktherownumberyouwanttohaltexecutiononandchooseAddbreakpoint.
Whenyouthenreloadthepage(orcausethecodetobeevaluatedsomeotherway),thebrowserwillstopatthebreakpointandgiveyoubunchofoptionshowtoproceed.
Someusefultoolshereinclude:
LookthroughtheScopelist.HerearelistedallthevariablesinLocal(currentfunctioncontext)scope,Closure(scopeofthefunctionthatinitiatedtheclosurecode),andGlobalscope.
WalkbackthroughtheCallStackmenu,asthiswillletyouinspectthefullexecutionthreadallthewaytowhereitwasinitialized.ThisisagreatwaytofindjustwheretheJavaScriptstartedbreakingdown.
Usethestepmethods(seescreenshotbelow)tocontinueprogressingthroughthecode,pausingaftereveryline.
Toremovethebreakpoint(goodideaonceyou’redonedebugging),expandtheBreakpointslistanduncheckthebreakpointsyouwanttodeactivate.
Searchthroughthesources
Sometimesitcanbeusefultosimplydoastringsearchthroughthesources.Forexample,ifyoufindGTM’sdataLayerisoverwritten,youcouldevensearchforsomethingassimpleasdataLayer=inordertofindifit’sbeenoverwrittenbycustomcodeinsomeotherfile.
YoucanfindthesearchtoolbyopeningtheDrawer(pressESC)andselectingtheSearchtab.Here,youcandoastringsearchanddevelopertoolswillsearchthroughallthesourcefilesforamatch.
Ifyoudofindamatch,youcanclickittojumptotherelevantpartofthesourcefile.
Addlocaloverrides
Thiscanbeextremelyhelpfulintestingyourpage.Youcanactuallyedit/add/removethingsinthepageHTMLorthelinkedJavaScriptresourcesbyaddinglocaloverrides.
Whenyougivethebrowserpermissiontowritelocaloverrides,youcanthenfreelyeditanyofthefilesintheSourcespanel,savethem,andwhenyoureloadthepagethesavedandmodifiedfilewillbeusedinsteadoftheoneloadedoverthenetwork.
InChrome,you’llseealittlepurplebuttonnexttothefileifithasalocaloverride.
Tostopusingoverrides,justopentheOverridestabintheSourcespanelanduncheck“EnableLocalOverrides”.
Applicationstorage
Theapplicationstoragetabshowsallthebrowserstorageusedonthecurrentpage(andinembeddedframes).
Thisincludesthingslikecookies,localStorage,andsessionStorage.
Youcanusethistabtocreate,edit,anddeleteitemsinbrowserstorage.
It’sagreatresourcetoidentifyproblemswithpersistenceinyouranalyticstools,forexample.
Herearesomeofthethingsyoucandowithapplicationstorage.
Inspectfirst-partyandthird-partystorage
It’sabitconfusing,butyoucanseemultipledomainsinboththenavigationcolumnaswellasintheactualstoragelist.
First,allthedomainslistedinthenavigationcolumn(simoahava.comandgtmtools.cominthescreenshotabove),representURLoriginsloadedinframes.Forexample,inthiscasesimoahava.comwastheURLofthetopframe,andthepageIwasonloadedaniframefromgtmtools.com.IntheApplicationtabIcanchoosegtmtools.comtoinspectthecookiesofthatparticularcontext.
Inthelistofcookies,ontheotherhand,ifyouseemultipledifferentdomainslistedit’sbecausethepageissendingrequeststothesedomains.Ifthebrowsersupportsthird-partycookies,you’llseeallthecookiessetonthedomainsthebrowseriscommunicatingwith.
Ifthebrowserblocksthird-partycookies,you’llonlyseecookiessetonthesiteofthetopframe(theURLtheuserisbrowsing).
Create,edit,anddeletestorage
Byclickinganystorageentryandpressingbackspace/delete,youcanremovethatparticularitemfromthebrowserstorage.
Youcaneditanystoragevaluesbydouble-clickingthevalueyouwanttoeditintherelevantcolumn.
Youcancreateanewcookie(orotherstorageentry)bydouble-clickingtheemptyrowatthebottomofthestoragelist.Youcantheninputanyvaluesyouwantintothecolumns.
Debugwebanalyticsimplementations
Onceyouhaveafeelforthedevelopertools,youcanstartdebuggingactualissueswithyourimplementations.
PleasenotethatsincethescopeofthingsyoucandowithJavaScriptissoimmenselyvast,it’simpossibletoexhaustivelylistallthethingsthatyoushoulddowhendebuggingyoursetup.
Inthischapter,I’velistedsomeofthemorecommonwaystoapproachimplementationissues.
Ifyouhaveother,commonusecasesyouthinkshouldbelistedhere,pleaseletmeknowinthecomments!
Checkbrowsercookies
Manyanalyticstoolsutilizebrowserstoragetopersistthingslikeuserandclientidentifiers.
GoogleAnalytics4usesthe_gaand_ga_
延伸文章資訊
- 1GA 工具Google Analytics Debugger 介紹及使用 - Let's Write
好,身為一個工程師,在不知道Google Analytics Debugger 這個工具以前,大概就是打開頁面的原始碼,然後找GA code。 這是廣告,點擊一下可以幫本站多個 ...
- 2Google Analytics Debugger 的評論– Firefox 附加元件站(zh ...
Google Analytics Debugger 的評論與評分。看看其他的使用者覺得Google Analytics Debugger 如何,再安裝進您的Firefox 瀏覽器。
- 3Google Analytics Debugger 的評論 - Firefox Browser Add-ons
Google Analytics Debugger 的評論與評分。看看其他的使用者覺得Google Analytics Debugger 如何,再安裝進您的Firefox 瀏覽器。
- 4Google Analytics Debugger Chrome 外掛幫你檢查程式碼
有沒有什麼方法可以確認自己網站已經把Google Analytics 分析的主要程式code 裝好了呢?答案是有的!它就是Google Analytics Debugger,然而它並不是個獨立可...
- 5Debug Guide For Web Analytics And Tag Management
GA Debugger is the official Universal Analytics, Google Analytics 4, and Google Tag Manager debug...