Article

Adding Picture in Picture to Your Safari Media Controls

Create a custom control that adds Picture in Picture to your Safari media player.

Overview

Although default controls are available for audio and video elements in your Safari webpage, you can also create your own custom media controls. One of the custom controls you should add is Picture in Picture. With Picture in Picture, your video remains in view in a floating video overlay while users interact with other apps.

Write Markup for a Custom Control

In this example, the custom controls for a video have only a Play button and a hidden Pause button:

Listing 1

This markup includes a set of pause and play controls for a video.

<video id="video" src="my-video.mp4"></video>
<div id="controls">
	<button id="playButton">Play</button>
	<button id="pauseButton" hidden>Pause</button>
</div>

Add a Picture-in-Picture Element to Your Markup

The custom controls now include markup for a new picture-in-picture button, which is visible by default.

Listing 2

This markup adds a picture-in-picture button to our previous controls.

<video id="video" src="my-video.mp4"></video>
<div id="controls">
	<button id="playButton">Play</button>
	<button id="pauseButton" hidden>Pause</button>
	<button id="PiPButton">PiP</button>
</div> 

Add Functionality to the Button

Add a function to toggle Picture in Picture using the webkitSetPresentationMode property from the presentation mode API.

Listing 3

This code toggles Picture in Picture using a click event listener.

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;
}

See Also

First Steps

Adding an AirPlay Button to Your Safari Media Controls

Create a custom control that adds AirPlay to your Safari media player.