I would like to pause the video when the user click on another tab in their browser. I have tried to do this with Youtube and Vimeo.
This is the basic idea behind the javascript:
For Youtube:
//YouTube
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 youtubePlayer;
var onYouTubeIframeAPIReady = function() {
youtubePlayer = new YT.Player('youtube', {
height: '390',
width: '640',
videoId: 'sXtekwuT8R0',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
};
var onPlayerReady = function(event) {
event.target.playVideo();
};
var onPlayerStateChange = function(event) {
if (event.data == YT.PlayerState.PLAYING) {
parent.focus();
window.onblur = function() {
status.text("You went away!");
youtubePlayer.stopVideo();
};
}
};
For Vimeo (using their Froogaloop library):
$(function() {
//Vimeo
var iframe = $('#vimeo');
var vimeoPlayer = $f(iframe[0]);
var status = $('#status');
vimeoPlayer.addEvent('ready', function() {
vimeoPlayer.addEvent('play', function(){
status.text("Playing!");
parent.focus();
window.onblur = function() {
status.text("You went away!");
vimeoPlayer.api("pause");
};
});
});
});
Here are some codepen examples of these attempts:
Youtube: http://codepen.io/earlonrails/pen/jugAm
Vimeo: http://codepen.io/earlonrails/pen/KBAmd
Both examples will work if after I click the play button, I click on the parent document of the iframe then click a different window or tab. The Youtube example will also work when it is first loaded, but not if you click the play then pause then play. I believe both of these problems are due to the fact that you are clicking the iframe, therefore the event either is trigger at the same time or cannot be triggered because the event can't be captured there. I thought using the postMessages sent through the iframes along with callbacks would make this work, but alas I have not been able to figure this out.
Need to set the current window before adding the event callback and use this window variable in the callback function. IE
var myWindow = window;
vimeoPlayer.addEvent('play', function(){
status.text("Playing!");
myWindow.focus();
myWindow.onblur = function() {
status.text("You went away!");
vimeoPlayer.api("pause");
};
});
These can be confirmed and tested at the previously linked codepen examples:
Youtube: http://codepen.io/earlonrails/pen/jugAm
Vimeo: http://codepen.io/earlonrails/pen/KBAmd
I guess the window when clicked in the iframe would be setting onblur on the iframe window, which would then never get called, but I still can't explain why when you click play on the iframe, then click the body of the page, then click a different tab then it works. Perhaps the callback is being fired more than once from the iframe or the postMessage is being fired or still in some buffer.