Tracking how many times an HTML5 audio element is

2019-04-07 22:46发布

问题:

What is the best way to track how many times an HTML5 audio element is played?

(we can use Google Analytics too, if that is the best approach)

回答1:

HTML5 Audio elements have basic callbacks.

You can combine that with a basic event callback library like jQuery to attach these events by default:

$("audio").bind("play", function(){
_gaq.push(["_trackEvent","Audio", "play", $(this).attr('src')]);
});

You can also do similar events for tracking when people finish the audio:

$("audio").bind("ended", function(){
_gaq.push(["_trackEvent","Audio", "ended", $(this).attr('src')]);
});

This can be made more concise by combining them into a single call:

$("audio").bind("play ended", function(e){
_gaq.push(["_trackEvent","Audio", e.type, $(this).attr('src')]);
});

You can also add the events on the <audio> tag attributes as onplay and onended, but, I wouldn't recommend that approach.



回答2:

If you upgraded to Universal Analytics and are not using classic analytics, then you would use a send event not a push event: ga('send', 'event', 'Audio', e.type, $(this).attr('src')); Also, if you were just testing this on your own, make sure you didn't create a filter to filter out your own IP address.