Has anyone managed to get the tracking of embedded YouTube video play/pause/ended working with the Monster Insights plugin for WordPress, or have an example where they have this working with Google universal.js? Please see below for the code I have so far. I have other GA Events being tracked successfully which are working fine, e.g. onclick="__gaTracker ('send', 'event', 'Mobile Call Button', 'call', 'mobile-call-button');"
<script>
// YouTube API
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_...";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This code is called by the YouTube API to create the player object
function onYouTubeIframeAPIReady(event) {
player = new YT.Player('decisions', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var pauseFlag = false;
function onPlayerReady(event) {
// do nothing, no tracking needed
}
function onPlayerStateChange(event) {
// track when user clicks to Play
if (event.data == YT.PlayerState.PLAYING) {
__gaTracker('send', 'event', 'Videos', 'Play', 'decisionsvideo');
pauseFlag = true;
}
// track when user clicks to Pause
if (event.data == YT.PlayerState.PAUSED && pauseFlag) {
__gaTracker('send', 'event', 'Videos', 'Pause', 'decisionsvideo');
pauseFlag = false;
}
// track when video ends
if (event.data == YT.PlayerState.ENDED) {
__gaTracker('send', 'event', 'Videos', 'Finished', 'decisionsvideo');
}
}
</script>
Related
We have lots of links on a landing page which are effectively to be tracked in Google ads as a conversion (outbound click). We're using the code below but clicks on the links aren't being registered in Google ads..
There is no further URL to call on hence "// window.location = url;"
function gtag_report_conversion(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
// window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-xxxxxxxxx',
'event_callback': callback
});
return false;
}
$(document).ready(function () {
$("#lp-id-10").click(function () {
gtag_report_conversion();
});
$(document).ready(function () {
$("#lp-id-11").click(function () {
gtag_report_conversion();
});
We've tried a few ways of coding this but our conversion point in Google ads is still marked as Unverified
I have following starting setup:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Then in onPlayerReady handler I added event listener to button which is outside iframe:
function onPlayerReady(event) {
button.addEventListener('click', () => event.target.playVideo());
}
In onPlayerStateChange I'm just logging what is happening:
function onPlayerStateChange(event) {
console.log(event.data);
}
After hitting that button in Chrome (v.72.0.3626.119) there are 3 entries in console: -1 (UNSTARTED), 3 (BUFFERING), -1 (UNSTARTED). When I try to hit button again nothing happens.
This works perfectly in Firefox, IE giving in console: -1 (UNSTARTED), 3 (BUFFERING),1 (PLAYING) and simply video starts playing.
Do you have any idea how to solve it?
You have to add in the onPlayerReady function this line:
event.target.playVideo();
As is shown in the documentation:
Example:
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
I can't say for sure why, but, in Google Chrome, for autoplay the video, you need to set the value 1 to the mute parameter, otherwise, autoplay the video wont work.
Example:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: '<YOUR_VIDEO_ID>',
playerVars: {
'autoplay': 1,
'loop': 1,
'mute': 1 // N.B. here the mute settings.
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
You can check this jsfiddle for guide yourself how you can set custom controls for play/pause your embed video.
I have sent a key after load html, and it works for me.
KeyEvent k = new KeyEvent();
k.WindowsKeyCode = 0x0D;
k.FocusOnEditableField = true;
k.IsSystemKey = false;
k.Type = KeyEventType.Char;
webytb.GetBrowser().GetHost().SendKeyEvent(k);
From this answer, Google Chrome need the allow="autoplay" attribute on iframe to let JS controls the player or make auto play function work.
This is required if you manually use <iframe> instead of <div> tag.
Example:
Attention! Please note that it maybe not work if the result iframe of this site don't have allow="autoplay" attribute on iframe. Copy and paste HTML & JavaScript into your .html file is the best way to test that it is really working.
var player;
/**
* Load YouTube API JavaScript
*/
function loadYTAPIScript() {
console.log('loading YouTube script.');
let tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
/**
* On YouTube iframe API ready
*
* This function will be called automatically by YouTube.
*/
function onYouTubeIframeAPIReady() {
console.log('function `onYouTubeIframeAPIReady` was called.');
player = new YT.Player('player', {
events: {
'onError': onError,
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onError(event) {
console.error('YouTube API error!', event);
} // _onError
/**
* On player ready.
*
* This is callback function from `onReady` event in `onYouTubeIframeAPIReady()`.
*/
function onPlayerReady(e) {
console.log('function `onPlayerReady` was called from `onReady` event callback.', e);
listClickButtons();
}
/**
* On player state change.
*
* This is callback function from `onStateChange` event in `onYouTubeIframeAPIReady()`.
*/
function onPlayerStateChange(e) {
console.log('function `onPlayerStateChange` was called from `onStateChange` event callback.', e);
let state = e.target.getPlayerState();
let stateText = '';
if (state === -1) {
stateText = 'unstarted';
} else if (state === YT.PlayerState.ENDED) {
stateText = 'ended';
} else if (state === YT.PlayerState.PLAYING) {
stateText = 'playing';
} else if (state === YT.PlayerState.PAUSED) {
stateText = 'paused';
} else if (state === YT.PlayerState.BUFFERING) {
stateText = 'buffering';
} else if (state === YT.PlayerState.CUED) {
stateText = 'cued';
}
console.log('State text: ', stateText);
}
/**
* Listen on click buttons to controls the video.
*
* This method was called from `onPlayerReady()`.
*/
function listClickButtons() {
console.log('Listen click buttons.');
let isPlayed = false;
let playpauseBtn = document.getElementById('yt-playpause');
let stopBtn = document.getElementById('yt-stop');
playpauseBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log('User click on play/pause button.');
if (isPlayed === false) {
player.playVideo();
isPlayed = true;
} else {
player.pauseVideo();
isPlayed = false;
}
});
stopBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log('User click on stop button.');
player.stopVideo();
});
}
document.addEventListener('DOMContentLoaded', (e) => {
console.log('DOM ready.');
loadYTAPIScript();
});
<iframe id="player"
width="560" height="315"
src="https://www.youtube.com/embed/1L904pgYbOE?enablejsapi=1"
title="YouTube video player"
allow="autoplay"
allowfullscreen=""
></iframe>
<!--
The `iframe` URL (`src` attribute) must contain enablejsapi=1 query string to let JS API work.
The `iframe` must contain `allow="autoplay"` attribute to allow JS controls the player.
-->
<div class="yt-controllers">
<button id="yt-playpause" type="button">
Play/Pause
</button>
<button id="yt-stop" type="button">
Stop
</button>
</div>
See full code on jsfiddle.
Reference:
Iframe
Iframe allow features list
YouTube Iframe API
I have a slideshow with youtube video's. But the problem now is that I can't trigger the onPlayerStateChange.
This is my code:
echo '<iframe id="youtube" src="http://www.youtube.com/embed/kOkQ4T5WO9E?enablejsapi=1&autoplay=1&rel=0</iframe>';
This is the JavaScript:
<script src="/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('youtube', {
events: { 'onStateChange': onPlayerStateChange }
});
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onPlayerStateChange(event) {
if (event.data === 0) {
alert('Video finished, next slide');
slide.next();
}
}
</script>
Is there a way to reload the iframe api when the video has ended?
I apologize, as last I knew, the YouTube API was entirely deprecated and almost no longer supported.
You're going to need to load new videos with the loadVideoByUrl function
player.loadVideoByUrl(mediaContentUrl:String,
startSeconds:Number,
suggestedQuality:String):Void
Also, you should change event.data === 0 to event.data == YT.PlayerState.ENDED
I'm trying to use basic onPlayerStateChange events in the Youtube IFrame API to track starts/stops/finishes in Google Analytics. The code worked in October, but now the video won't display. GA tracking code is the same and I get the same results in Wordpress and Drupal. Is it changes to the API?
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '461',
width: '560',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data ==YT.PlayerState.PLAYING)
{_gaq.push(['_trackEvent', 'Videos', 'Play', ‘AnyEvent’ ]); }
if (event.data ==YT.PlayerState.ENDED)
{_gaq.push(['_trackEvent', 'Videos', 'Watch to End', ‘AnyEvent’]); } }
</script>
<div id="player"></div>
Those are curly-single-quotes around ‘AnyEvent’, right? That's not valid JavaScript.
I have embeded some youtube videos in my website. I want to track the views of each videos with google analytics, but I cannot catch any onClick event because the videos are embeded in using iFrame. How can I track the views of youtube videos that is embeded in my webpage using iFrame ?
I've been using YouTube's API to track plays as events in Google Analytics. It's the same format in iFrame API and javascript. Look at the iFrame API if you want to track other functions. This is where I originally got the event tracking information.
You'll have to change the videoID below:
<div id="player"></div>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'fYmrMt01S1U',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
/// event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
_gaq.push(['_trackEvent', 'Videos', 'Play',
player.getVideoUrl()]);
}
if (event.data == YT.PlayerState.PAUSED) {
_gaq.push(['_trackEvent', 'Videos', 'Paused',
player.getVideoUrl()]);
}
if (event.data == YT.PlayerState.ENDED) {
_gaq.push(['_trackEvent', 'Videos', 'Watch to End',
player.getVideoUrl()]);
}
}
// ]]>
</script>