Send data to Google Analytics with gtag.js

文章推薦指數: 80 %
投票人數:10人

This page describes how to use gtag.js commands to send data from your site to Google Analytics. Send data with the event command. Google Analytics Measurement UniversalAnalytics(gtag.js) Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Google Analytics Measurement UniversalAnalytics(gtag.js) Guides Getstarted Addgtag.jstoyoursiteSenddatatoGoogleAnalyticsSetpersistentvalues Measurecommonuserinteractions PageviewsEventsPhoneanalyticsApp/screenviewsUsertimingsExceptions Advanced CookiesanduseridentificationCross-domainmeasurementCustomdimensionsandmetricsDisableadvertisingfeaturesEnhancedecommerceEnhancedlinkattributionIPanonymizationRenametheglobalobjectDisableAnalyticsforopted-outusers Solutions CheckexceptionsandcustomdimensionsandmetricsSinglepageapplications Resources CookieusageLimitsandquotas Home Products GoogleAnalytics Measurement UniversalAnalytics(gtag.js) SenddatatoGoogleAnalyticswithgtag.js Thispagedescribeshowtousegtag.jscommandstosenddatafromyoursitetoGoogleAnalytics. Senddatawiththeeventcommand Onceyou'veaddedtheglobalsnippettoawebpage,usetheeventcommandtosenddatatoGoogleAnalytics.Forexample,usethefollowingeventcommandtoindicatethatauserhassignedinusingtheirGoogleaccount: gtag('event','login',{'method':'Google'}); LearnmoreabouttheeventcommandintheAPIreference. Routedatatogroupsandproperties YoucansendonesetofmeasurementinformationtooneormoreGoogleAnalyticspropertyIDs,andanothersetofinformationtootherpropertyIDs.Youcanorganizepropertiesintogroupsandroutedatatothem. Forexample,thefollowingcodeexampleillustrateshowtorouteasign_ineventtoagroup'agency'thatincludestwoGoogleAnalyticsproperties. //Configureatarget gtag('config','GA_MEASUREMENT_ID_1'); gtag('config','GA_MEASUREMENT_ID_2',{'groups':'agency'}); gtag('config','GA_MEASUREMENT_ID_3',{'groups':'agency'}); //Routethissign_ineventtoAnalyticsIDsinthe'agency'group: gtag('event','sign_in',{'send_to':'agency'}); Learnmoreabouthowtogroupandroutedata. Knowwhenaneventhasbeensent Insomecases,youneedtoknowwhenaneventhasbeensuccessfullysenttoGoogleAnalytics,soyoucantakeactionimmediatelyafterward.Thisiscommonwhenyouneedtorecordaparticularinteractionthatwouldtakeauserawayfromthecurrentpage.ManybrowsersstopexecutingJavaScriptassoonasthenextpagestartsloading,whichmeansyourgtag.jseventcommandsmayneverrun. Forexample,youmaywanttosendaneventtoGoogleAnalyticstorecordthatauserhasclickedonaform'ssubmitbutton.Inmostcases,clickingthesubmitbuttonwillimmediatelystartloadingthenextpagebeforeanyeventcommandshaveachancetoexecute. ThesolutionistointercepttheeventtostopthenextpagefromloadingsothatyoucansendtheeventtoGoogleAnalytics.Aftertheeventhasbeensent,submittheformprogrammatically. Implementeventcallbackfunctions Youcanimplementaneventcallbackfunctionthatgetscalledassoonasaneventhasbeensuccessfullysent. Thefollowingexampleshowshowtocancelaform'sdefaultsubmitaction,sendaneventtoGoogleAnalytics,andthenresubmittheformusingtheeventcallbackfunction: //Getareferencetotheformelement,assuming //itcontainstheIDattribute"signup-form". varform=document.getElementById('signup-form'); //Addalistenerforthe"submit"event. form.addEventListener('submit',function(event){ //Preventthebrowserfromsubmittingtheform //andthusunloadingthecurrentpage. event.preventDefault(); //SendtheeventtoGoogleAnalyticsand //resubmittheformoncethehitisdone. gtag('event','signup_form_complete',{ 'event_callback':function(){ form.submit(); } }); }); Handletimeouts Thereisonedrawbacktotheaboveexample:Ifthegtag.jslibraryfailstoload,theeventcallbackfunctionwillneverrunanduserswillneverbeabletosubmittheform. Wheneveryouputcriticalsitefunctionalityinsidetheeventcallbackfunction,youshouldalwaysuseatimeoutfunctiontohandlecaseswherethegtag.jslibraryfailstoload. Thefollowingexampleenhancestheabovecodetouseatimeout.Ifonesecondpassesaftertheuserclicksthesubmitbuttonandtheeventcallbackfunctionhasnotrun,theformisresubmittedanyway. //Getsareferencetotheformelement,assuming //itcontainstheIDattribute"signup-form". varform=document.getElementById('signup-form'); //Addsalistenerforthe"submit"event. form.addEventListener('submit',function(event){ //Preventsthebrowserfromsubmittingtheform //andthusunloadingthecurrentpage. event.preventDefault(); //CreatesatimeouttocallsubmitFormafteronesecond. setTimeout(submitForm,1000); //Monitorswhetherornottheformhasbeensubmitted. //Thispreventstheformfrombeingsubmittedtwiceincases //wheretheeventcallbackfunctionfiresnormally. varformSubmitted=false; functionsubmitForm(){ if(!formSubmitted){ formSubmitted=true; form.submit(); } } //SendstheeventtoGoogleAnalyticsand //resubmitstheformoncethehitisdone. gtag('event','signup_form_complete',{ 'event_callback':submitForm }); }); Ifyouusetheabovepatternthroughoutyoursite,createautilityfunctiontohandletimeouts. Thefollowingutilityfunctionacceptsafunctionasinputandreturnsanewfunction.Ifthereturnedfunctioniscalledbeforethetimeoutperiod(thedefaulttimeoutisonesecond),itclearsthetimeoutandcallstheinputfunction.Ifthereturnedfunctionisn'tcalledbeforethetimeoutperiod,theinputfunctioniscalledregardless. functioncreateFunctionWithTimeout(callback,opt_timeout){ varcalled=false; functionfn(){ if(!called){ called=true; callback(); } } setTimeout(fn,opt_timeout||1000); returnfn; } Now,youcanwrapalleventcallbackfunctionswithatimeouttoensureyoursiteworksasexpected,evenincaseswhereyoureventsfailtosendorthegtag.jslibraryneverloads. //Getsareferencetotheformelement,assuming //itcontainstheIDattribute"signup-form". varform=document.getElementById('signup-form'); //Addsalistenerforthe"submit"event. form.addEventListener('submit',function(event){ //Preventsthebrowserfromsubmittingtheform //andthusunloadingthecurrentpage. event.preventDefault(); //SendstheeventtoGoogleAnalyticsand //resubmitstheformoncethehitisdone. gtag('event','signup_form',{'event_callback':{ createFunctionWithTimeout(function(){ form.submit(); }) }}); }); Specifydifferenttransportmechanisms Bydefault,gtag.jspickstheHTTPSmethodandtransportmechanismwith whichtooptimallysendhits.Thethreeoptionsare: 'image'(usinganImageobject) 'xhr'(usinganXMLHttpRequestobject) 'beacon'(usingthenavigator.sendBeaconmethod) Thefirsttwomethodssharetheproblemdescribedintheprevioussection,wherehitsarenotsentifthepageisbeingunloaded.Thenavigator.sendBeaconmethodsolvesthisproblembyasynchronouslytransmittinghitstothewebserverwithouthavingtosetahitcallback. Thefollowingcodesetsthetransportmechanismto'beacon'forbrowsersthatsupportit: gtag('config','GA_MEASUREMENT_ID',{'transport_type':'beacon'}); Currently,gtag.jsonlyusesnavigator.sendBeaconifthe transportmechanismissetto'beacon'.However,inthefuture, gtag.jswilllikelyswitchtousing'beacon'asthedefault mechanisminbrowsersthatsupportit. Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2021-06-10UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] GitHub TryGoogleAnalyticssamples StackOverflow Askquestionsusingthegoogle-analyticstag Twitter Follow@googleanalyticsonTwitter Videos ViewGoogleAnalyticsvideosonYouTube Connect Community&Updates GettingHelp ReportinganIssue ProductInfo Protocol/SDKPolicy BrandingPolicy Developerconsoles GoogleAPIConsole GoogleCloudPlatformConsole GooglePlayConsole FirebaseConsole ActionsonGoogleConsole CastSDKDeveloperConsole ChromeWebStoreDashboard Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어



請為這篇文章評分?