Como medir vídeos YouTube com Google Analytics
Se você tem vídeos postados no YouTube já deve saber que é possível analisar estatísticas e métricas avançadas sobre a visualização da sua obra de arte através do YouTube Insights. Para quem não conhece é um recurso espetacular do YouTube que fornece dados de origem, dados demográficos e até de tempo de visualização dos seus vídeos.
Porém, se você gosta de incorporar os vídeos em sua página ou blog, já deve ter passado pela frustração de não saber quanto do seu vídeo é visto pelos seus visitantes, ou ao menos quantas pessoas chegaram até o final do vídeo.
Mas, e o Google Analytics, não pode medir isso?
Bom, por padrão é difícil, afinal um vídeo YouTube incorporado (embedded) é um player flash que não pode ser editado. Mas, como gostamos de desafios, sejam eles quais forem (e quanto mais nerd melhor) não desistimos!
Garimpando um pouco a API do Youtube, encontramos maneiras de monitorar os eventos de vídeo, e, com um pouquinho de força mental (e alguns parâmetros no player), já é possível monitorar estes eventos e enviar as informações para o Google Analytics com um simples código javascript.
Inspirados assim, desenvolvemos uma pequena biblioteca javascript que permite ligarmos os vídeos Youtube incorporados em qualquer página a um tracking de eventos para o Google Analytics. Nós também abrimos o código-fonte no Google Code (ga-youtube-tracker) para que mais pessoas possam se beneficiar, customizar e melhorar a biblioteca. Participe
Para usar a biblioteca é simples:
- Adicione um ID para o elemento flash do player incorporado à página
- Adicione à URL do vídeo Youtube os parâmetros: &enablejsapi=1&playerapiid=ID_DO_ELEMENTO_FLASH
- Faça o download do arquivo Javascript da biblioteca Google Analytics for YouTube e hospede no seu servidor
- Inclua uma chamada para a biblioteca na sua página que contem o(s) vídeo(s)
Fácil não?
Temos que nos preocupar somente com 1 detalhe técnico para viabilizar tudo isso:
- No Internet Explorer, alguns recursos da API do YouTube não podem ser executadas com o player incorporado direto como um elemento HTML (OBJECT / EMBED), então, utilize a biblioteca SWFObject para incorporar o player de vídeo.
Vejam como fica o código de uma página simples de exemplo:
<!--SWF Object Reference needed to cross-browser embedding the player--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script> <!--YouTube Embedded Code - Video 1--> <div id="flashdiv1"></div> <script type="text/javascript"> var params = { allowScriptAccess: "always" }; var atts = { id: "myplayerid1" }; swfobject.embedSWF("http://www.youtube.com/v/gRvUpoTT-Bo&hl=pt-br&fs=1&enablejsapi=1&playerapiid=myplayerid1", "flashdiv1", "425", "344", "8", null, null, params, atts); </script> <!--Youtube tracking component--> <script src="ga_dpc_youtube.js"></script> <!--Initializing component--> <script> try{ var ytTracker = new YoutubeTracker(); }catch(e){} </script>
A biblioteca monitora o vídeo incorporado e dispara os seguintes eventos para a interface de rastreamento de eventos do Google Analytics:
- Cued (vídeo preparado)
- Play
- Paused
- Ended (chegou no final)
- Fast-Forward (avançou)
- Rewind (retrocedeu)
- View-Range (quanto do vídeo já visualizou)
Para cada um dos eventos disparados, a biblioteca inclui uma marcação indicando em qual parte do vídeo aquele evento ocorreu. É possível por exemplo saber em quantos segundos do vídeo os visitantes avançam mais o vídeo ou param a execução. Ou ainda saber se eles visualizam até metade do vídeo, ou até o final, etc.
Veja como fica nos relatórios:
As categorias de eventos são definidas como youtube-video:Id-do-vídeo-YouTube:
Fazendo drill-down em algum vídeo específico, você verá que as ações são nada mais que os eventos do vídeo (cued, play, paused, ended, fast-foward, rewind):
E se você clicar em cada ação, verá que cada ação está associado a uma parte do vídeo em faixas de tempo de visualização:
Essas faixas (chamadas “buckets”) são definidas por padrão como as faixas de duração de visitas do Google Analytics em segundos (0-9, 10-29, 30-59, 60-179, 180-599, 600+). É possível, porém personalizar estas faixas passando o parâmetro opt_bucket para o método de inicialização da biblioteca na página. Veja o exemplo (definindo as faixas por segundos para 0-29, 30-59, 60-89, 90-119, 120+):
<script> try{ var ytTracker = new YoutubeTracker([30,60,90,120]); }catch(e){} </script>
Simples não?
Keep on tagging!









O trabalho ficou simplesmente perfeito!!! Já parei o que estava fazendo para testar..
Obrigado por compartilhar!
30 / April / 2010 às 07:23 por Marcelo Namura
O os parâmetros foram corretamente enviados. Agora vou aguardar para visualizar no Analytics.
Muito bom, parabéns pessoal
13 / May / 2010 às 01:06 por Adalberto G. da Costa
Obrigado Marcelo e Adalberto!
Por favor compartilhem suas experiências
Qualquer problema só avisar, ou então enviar os bugs na página do projeto:
http://code.google.com/p/ga-youtube-tracker/issues/list
Abs!
13 / May / 2010 às 08:47 por Leonardo Naressi
Pessoal,
No meu caso eu mandei customizar meu próprio player para poder usar o banner no player (coisa que videos embedados não me dariam).
No meu caso eu posso ter este controle?
Eu já reparei que posso contar com o relatorio da locaweb para alguns controles assim, mas no caso do canal que criei não sei como fazer (canal bauma: http://www.tvdaobra.com.br/bauma)
aproveitando… vcs acharam uma boa ideia eu ter mandado fazer um player só pro meu portal??
20 / May / 2010 às 04:45 por alexandre
Apliquei o script no vídeo que aparece na home desse site: http://orquestra.casamentoecerimonia.com.br/
Ficou ótimo e me ajudou a determinar qual é o vídeo que performa melhor cruzando número de visualizações e conversões.
Valeu pessoal.
Adalberto
25 / May / 2010 às 02:02 por Adalberto G. da Costa
Alexandre,
Com seu player customizado não será possível fazer este tracking de maneira automática com o nosso script.
Acho uma boa idéia sim você customizar o Player pois fica com uma estética muito boa customizada para o seu site. Porém o player que foi escolhido (flv-player.net) não possui nenhuma opção para medição com o Google Analytics.
Recomendo você testar o player JW FLV Player que possui um bom plugin para medição no Google Analytics.
[]s
28 / May / 2010 às 08:24 por Leonardo Naressi
Obrigado pelo feedback Adalberto!
Tomei a liberdade de adicionar você numa pequena lista dos sites que já implementaram ou testaram o script:
http://code.google.com/p/ga-youtube-tracker/wiki/SitesWhoImplemented
[]s
28 / May / 2010 às 08:31 por Leonardo Naressi
Opa, estamos aí!
02 / June / 2010 às 08:51 por Adalberto G. da Costa
Added uri decoding…
// e.g. transform ‘yt%5Fplayer’ into ‘yt_player’
playerId = decodeURI(playerId);
19 / October / 2010 às 10:49 por Jason
Eu tenho como monitorar algum outro tipo de video, alem dos q estao no youtube? Como vimeo ou outros???
20 / October / 2010 às 09:41 por Ju Marfil
O Vimeo possui uma API semelhante ao YouTube então é sim possível fazer tracking de Vimeo usando a mesma lógica, estamos planejando uma atualização futura da tag com suporte a outros videos.
O JWPlayer é um bom pago que possui um plugin para google analytics.
Se tem interesse para suporte a outros players vale a pena colocar um bug no issue tracker do projeto:
21 / October / 2010 às 06:36 por Eduardo Cereto
Hi!
This code looks awesome! I am trying to desperately to get this code to work on my site, but it doesn’t seem to want to play ball….
My question is, where do you need to add the JS snippet to generate the ytTracker object in relation to where you generate the standard yt pageTracker object?
If i can explain the order in which i am adding js files, generating objects…would you be able to advise on this ordering, or whether i am missing anything? (I am using Drupal for my site):
1. include swfobject js file in
2. include your ga_dpc_youtube.js file in
3. Then use swfobjet.embedSWF to embed my video. Pass id into object and also add the params “&enablejsapi=1&playerapiid=myplayerid1″ onto the embed source. This is done within middle of body section of page.
4. Include google analytics js file towards bottom of body. (This is a file used by Google Analytics module within Drupal)
5. Embed javascript which generates ytTracker object. “var ytTracker = new YoutubeTracker();”
6. Embed javascript which generates my pageTracker object for standard GA tracking.
Should i be ordering my code slightly differently? Or am i missing something here? Any help would be gratefully received!
cheers
Craig
31 / October / 2010 às 08:08 por Craig Barber
I can’t see the issue if you don’t send me your code. Maybe you’re missing the id on the parent element of te flash object.
Check our wiki page on google code if you can’t manage to work please fill a bug there on google code.
thanks.
http://code.google.com/p/ga-youtube-tracker/wiki/HowToTrackEmbeddedYoutubeWithGoogleAnalytics
03 / November / 2010 às 01:48 por Eduardo Cereto
Olá, implementei o código de monitoramento conforme orientações aqui porém não está monitorando os eventos lá no alnalytics.
Como posso verificar onde está o erro ?
Segue abaixo o código implementado no meu site.
var params = { allowScriptAccess: “always” };
var atts = { id: “vid_dicas-para-escolher-a-sua-agencia” };
swfobject.embedSWF(“http://www.youtube.com/v/WVPT28ByNZ0?fs=1&hl=en_US&enablejsapi=1&playerapiid=vid_dicas-para-escolher-a-sua-agencia”, “flashdiv1″, “425″, “295″, “9″, null, null, params, atts);
try{
var ytTracker = new YoutubeTracker();
}catch(e){}
Obrigado e no Aguardo.
08 / November / 2010 às 11:03 por Adriano
Olá Adriano, O ideal seria você enviar um link com a implementação que você fez para que possamos verificar o que pode ter ocorrido.
Pelo seu código o que consigo perceber é que você não incluiu o arquivo js. Você precisa baixar este arquivo da página do projeto no Google code e inclui-lo antes da chamada ao YoutubeTracker().
<script src=”ga_dpc_youtube.js”></script>
16 / December / 2010 às 02:59 por Eduardo Cereto
Hi Leonardo,
Just wanted to say thanks for this – You guys were impressive on the GA summit and this is just another proof. Well done!
20 / December / 2010 às 06:19 por Boaz Ariely
Thanks very much for releasing your code! It works great for me in an ordinary window, but do you know if it’s possible to use it to track videos in an overlay window such as Fancybox?
03 / January / 2011 às 01:31 por Zoe
I’d love to add this code to track video plays on my site, but I’m too bad with javascript to understand your sample instructions.
1. The following line of code looks very similar to one that’s in the header of my pages to control menus. Does it go in the header?
2. Is this line of code shorthand for the entire div that contains the YouTube embed, meaning that the rest of the code should just be dropped under it, outside of the video div?
3. I actually use the same ID for all three of the videos on my site because they sit in exactly the same page position and it’s easy for CSS. Do I have to give them all separate IDs and add each ID to the end of the YouTube SRC or can I stick with one?
07 / January / 2011 às 08:26 por Andrew Smith
Sorry, I pasted lines of code in my comment, but they didn’t come through.
Let me put it a different way.
1. Does any of your code go in page headers or does it all go in the body section?
2. Does all of the code go within the Div that actually contains the Youtube embed or does it go before and after?
3. If I use the same ID for my videos, can I keep it that way — and let GA sort them by SRC — or do they need individual names?
07 / January / 2011 às 08:29 por Andrew Smith
Thank you Zoe!
It’s possible to track Fancybox overlay videos but you need to make sure to use swfobject to render the video object and use the proper IDs and youtube params described otherwise the Youtube API will not fire the onYoutubePlayerReady event.
Check this posts on using Fancybox with swfobject:
http://jquery.diaz-cornen.com/fancybox/index_flash.html
http://www.bensonarts.com/jquery/creating-a-youtube-gallery-using-jquery-fancybox/
08 / January / 2011 às 01:08 por Leonardo Naressi
Hi Andrew,
So, here we go:
1. the youtube tracker can be placed on any section of the page, because it only build a common method that will be called by the Youtube Player. So, feel free to put it on HEAD or BODY section.
2. You don’t need to place the code near the video player Div, but you need to make sure to specify the proper param in the Youtube URL (&enablejsapi=1&playerapiid=FLASH_ELEMENT_ID)
3. You can use the same ID for all of your Videos, because the code you send the Youtube video code (on SRC) as the identifier in GA reports.
Let me know if it helps you!
Thanks
08 / January / 2011 às 01:15 por Leonardo Naressi
Can I use this on videos that I encoded and not a youtube video? Is it possible? I’m having a hard time finding resources that can walk me through this kind of tracking. Hard to believe that I’m the only one who wants to track my own videos!
Thanks!
07 / February / 2011 às 10:42 por Hombre
I’m having trouble triggering the tracking in debug of a player loaded via .
Here is my testing file http://www.stopthatrobot.com/test2.html . The tracking is functioning on the player called via swfobject.embedSWF, however I can’t use this for mobile devices.
Any thoughts would be appreciated.
08 / February / 2011 às 11:12 por val
This won’t work with mobile devices since it relies on swfobject, which embeds flash. There’s a new iframe API from YouTube which is still experimental (labs) but does support mobile devices.
12 / April / 2011 às 02:36 por Mike Plummer
Thanks Mike! This solution is not yet compatible with the new Youtube iFrame API, we are playing and testing the new features.
I’ve opened an issue, if you would like to track this development or to contribute: http://code.google.com/p/ga-youtube-tracker/issues/detail?id=6
Thanks again!
14 / April / 2011 às 03:58 por Leonardo Naressi
Excellent! I was having a great trouble trying to build the script since I’m not a programmer, but your tool helped me a lot.
Thanks a lot!
22 / May / 2011 às 03:56 por Pablo Contreras
Hey Guys,
Fantastic to see this development however I’m at my wits end in getting it to work.
Would it be possible for someone to check out my test page at http://www.geekandjock.com/blogs/thegeek/even-healthy-relationships-have-arguments and let me know what I’m doing wrong.
As far as I can see, I’ve done all the right things but it’s failing to show up on GA so I’m convinced I’m doing something obviously wrong (just not obvious to me).
Any help would be really appreciated.
Cheers
Martin
16 / June / 2011 às 03:51 por Healthy Relationships
OK – found the reason.
This JS script isn’t compatible with asynchronous tracking – http://code.google.com/p/ga-youtube-tracker/issues/detail?id=7
Hopefully this will be fixed soon – thanks for your efforts, guys
19 / June / 2011 às 01:30 por Healthy Relationships
Thanks Martin! I’ve justed fixed the Asynx default compatibility. I hope it helps!
04 / August / 2011 às 08:46 por Leonardo Naressi
I’m really confused about how to get this working in Internet Explorer. Help?
22 / August / 2011 às 08:13 por Nicole Hanusek
any chance of making it work with iframe embeds please?
16 / November / 2011 às 08:25 por milllan
iframe
20 / December / 2011 às 04:24 por domaći filmovi
Muito bom. agora sabes dizer se parou de funcionar o “playing”.
if(action==’playing’){
_gaq.push(["_trackEvent","categoria","video","alguma"]);
}
18 / January / 2012 às 01:29 por Lucas Cavalcanti
@Lucas and dear visitors,
there’s a brand new script developed by Eduardo Cereto that works with IFRAME and it’s simpler to understand.
Check it out:
https://github.com/eduardocereto/GA-Code-Samples/blob/master/src/youtube.js
Hope it fits better to you!
Thanks for your visit!
18 / January / 2012 às 07:23 por Leonardo Naressi
Did anyone try the fix for iframe from Eduardo? I tried it but it’s not tracking. I call the JS file in my header then I added enablejsapi=1 in the youtube Iframe url.
28 / February / 2012 às 01:44 por Ken
Muy buen artículo¡¡¡ Esto es analítica avanzada para mí pues me ha costado entender el idioma. Hablas de Youtube, pero a los videos de vimeo se pueden hacer eventos en Analytics? Gracias¡¡¡¡
25 / May / 2012 às 06:20 por Marta