Lately i faced an interesting problem when trying to use the picture in picture API with a video tag that loaded a remote WebRTC stream from Janus. When trying to request the PiP API in the video element like this, using the following method:
/**
* Request Picture in Picture of Video.
*
* @param {HTMLVideoElement} videoElement
* @returns {undefined}
*/
function enterPictureInPicture(videoElement) {
if(document.pictureInPictureEnabled && !videoElement.disablePictureInPicture) {
try {
if (document.pictureInPictureElement) {
document.exitPictureInPicture();
}
videoElement.requestPictureInPicture();
} catch(err) {
console.error(err);
}
}
}
// Request on my dom element
enterPictureInPicture(document.getElementById("myvideo"));
The mentioned exception Failed to execute 'requestPictureInPicture' on 'HTMLVideoElement': Metadata for the video element are not loaded yet
appeared everytime i tried to request it. The solution is very simple though, you will need to wait until the metadata of the video has been correctly loaded to request the PIP API like this:
let videoElement = document.getElementById("myvideo");
videoElement.onloadedmetadata = function() {
// You should be able to request the picture in picture API from here
// Request on my dom element
enterPictureInPicture(document.getElementById("myvideo"));
};
You should usually do this when you work with heavy videos that doesn't load immediately or either with WebRTC streams that usually take a while until they load into the video tag. Requesting the picture in picture (PiP) API just after this callback is triggered, shouldn't trigger the mentioned exception.
Happy coding ❤️!