问题
I've got a video on our website that I'm tracking the views of using Google Analytics. This is the code:
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var utm_source='<?php echo $utm_source ?>';
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'xxxxxxxxxx',
frameborder: '0',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
// Uncomment the event to have video start automatically.
function onPlayerReady(event) {
// event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
if (utm_source == 'zilch') {
ga('send', 'event', 'YouTube', 'Started', 'Promo from Main Page');
}
else if (utm_source == 'CAMPAIGN') {
ga('send', 'event', 'YouTube', 'Started', 'Promo from Main Page via CAMPAIGN');
}
else {
ga('send', 'event', 'YouTube', 'Started', 'Promo from Main Page');
}
}
if (event.data == YT.PlayerState.ENDED) {
if (utm_source == 'zilch') {
ga('send', 'event', 'YouTube', 'Finished', 'Promo from Main Page');
}
else if (utm_source == 'CAMPAIGN') {
ga('send', 'event', 'YouTube', 'Finished', 'Promo from Main Page via CAMPAIGN');
}
else {
ga('send', 'event', 'YouTube', 'Finished', 'Promo from Main Page');
}
}
}
</script>
If I copy and paste this code, and change the video ID it overwrites the original. If I copy and paste this code, and leave the video ID instead of showing two it just shows the original.
How can I work this so I have more then one video being tracked on the page? I'm thinking it has to do with the <div id='player'></div>
but am not seeing how to change the target div.
回答1:
How I ended up working around this is using Nevo Lightbox. I then created a thumbnail for each video and linked it somewhat like so:
<a href='https://www.youtube.com/watch?v=videoID' data-lightbox-gallery='playlist' title='Video description' onclick="ga('send', 'event', 'Video', 'Play', 'Demo on videos');">
Changing the VideoID and Video Description. There's probably a more elegant solution, but its getting the job done.
来源:https://stackoverflow.com/questions/23634106/how-can-i-track-two-videos-on-one-page-using-google-analytics-and-youtube-api