TheCrazyProfessor TheCrazyProfessor - 1 month ago 27
Javascript Question

Safari - HTML5 video Picture In Picture (PiP)

Safari HTML5 custom video controller with Picture In Picture (PiP)

At the WWDC16 Apple introduces Safari 10, there now have support for Picture in Picture.

The button is there for html5 video standard controls, but how do I trigger it by javascript?


If you use custom HTML5 video controls, you can add Picture in Picture
functionality using the JavaScript presentation mode API.


Apple Picture In Picture on macOS Sierra



<video controls id="video" width="320">
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>




Answer

After a lot more research, i have found the webkit JS, API

This is Picture-in-Picture

if (video.webkitSupportsPresentationMode && typeof video.webkitSetPresentationMode === "function") {
    // Toggle PiP when the user clicks the button.
    pipButtonElement.addEventListener("click", function(event) {
        video.webkitSetPresentationMode(video.webkitPresentationMode === "picture-in-picture" ? "inline" : "picture-in-picture");
    });
} else {
    pipButtonElement.disabled = true;
}

Airplay

if (window.WebKitPlaybackTargetAvailabilityEvent) {
    video.addEventListener('webkitplaybacktargetavailabilitychanged',
        function(event) {
           switch (event.availability) {
                case "available": /* turn stuff on */
                break;
                case "not-available": /* turn AirPlay button off */
                break;
           }
        })
}




In action

var video = document.getElementById('video');
var airPlay = document.getElementById('airplay');
var PiP = document.getElementById('picture-in-picture');

// picture-in-picture
if (video.webkitSupportsPresentationMode && typeof video.webkitSetPresentationMode === "function") {
    // Toggle PiP when the user clicks the button.
    PiP.addEventListener("click", function(event) {
        video.webkitSetPresentationMode(video.webkitPresentationMode === "picture-in-picture" ? "inline" : "picture-in-picture");
    });
} else {
    PiP.disabled = true;
}



// Airplay
if (window.WebKitPlaybackTargetAvailabilityEvent) {
	video.addEventListener('webkitplaybacktargetavailabilitychanged', function(event) {
		switch (event.availability) {
			case "available":
				airPlay.style.display = 'block';
				break;
			default:
				airPlay.style.display = 'none';
		}
		airPlay.addEventListener('click', function() {
			video.webkitShowPlaybackTargetPicker();
		});
	});
}else {
	airPlay.style.display = 'none';
}
<video controls id="video" x-webkit-airplay="allow" width="320"> 
	<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">		
</video>
	
<div class="controls">
	<button id="picture-in-picture">Picture in Picture</button>
	<button id="airplay">Airplay</button>
</div>