我需要从页面上的多个iframe中获取ga事件标签,但它只能使用第一个iframe而不是第二个iframe。我正在使用的代码如下。我尝试过使用每个功能但没有运气。
try {
var checkYoutubeIframe = false;
//Verify all iFrames from the page
$("iframe").each(function () {
//Check if you a YT iFrame
if ($(this).attr('src').indexOf("youtube.com/embed") >= 0) {
checkYoutubeIframe = true;
//Add the YT ID
if ($(this).attr('id') == undefined ||$(this).attr('id').indexOf("youTubePlayer2") == -1) {
$(this).attr('id', 'youTubePlayer2')
}
//Add Enable JS API parameter
if ($(this).attr('src').indexOf("enablejsapi=1") == -1) {
if ($(this).attr('src').indexOf("?") >= 0) {
var src = $(this).attr('src') + "&enablejsapi=1"
$(this).attr('src', src)
} else {
var src = $(this).attr('src') + "?enablejsapi=1"
$(this).attr('src', src)
}
}
}
})
//Call logic if there is an iFrame on the page
if (checkYoutubeIframe) {
//Include YT API
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//Call the YT Tracker Function
function onYouTubeIframeAPIReady(event) {
player = new YT.Player('youTubePlayer2', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {}
//Tracker
function onPlayerStateChange(event) {
var label = player.getVideoUrl();
// track when user clicks to Play
if (event.data == YT.PlayerState.PLAYING) {
ga('send', 'event', 'Engagement', 'Play', label );
}
// track when user clicks to Pause
if (event.data == YT.PlayerState.PAUSED) {
ga('send', 'event', 'Engagement', 'Pause', label );
}
// track when user clicks to Pause
if (event.data == YT.PlayerState.ENDED) {
ga('send', 'event', 'Engagement', 'Watch to End', label );
}
}
}
} catch (e) {}
答案 0 :(得分:0)
嗯,我认为这有点改变了代码,但这里是结束代码并且有效。
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var youtubePlayer1;
var youtubePlayer2;
function onYouTubeIframeAPIReady() {
youtubePlayer1 = new YT.Player('player1', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
youtubePlayer2 = new YT.Player('player2', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {}
function onPlayerStateChange(event) {
var label = event.target.getIframe().src;
if (event.data == YT.PlayerState.PLAYING) {
ga('send', 'event', 'YT Videos', 'Play', label);
pauseFlag = true;
}
if (event.data == YT.PlayerState.ENDED) {
ga('send', 'event', 'YT Videos', 'Finished', label);
} else if (event.data == YT.PlayerState.PAUSED && pauseFlag) {
ga('send', 'event', 'YT Videos', 'Pause', label);
pauseFlag = false;
}
}