diff --git a/plugins/picture-in-picture/front.js b/plugins/picture-in-picture/front.js index 788a908e..5d0bf302 100644 --- a/plugins/picture-in-picture/front.js +++ b/plugins/picture-in-picture/front.js @@ -5,6 +5,7 @@ const { ElementFromFile, templatePath } = require("../utils"); function $(selector) { return document.querySelector(selector); } +let useNativePiP = false; let menu = null; const pipButton = ElementFromFile( templatePath(__dirname, "picture-in-picture.html") @@ -39,8 +40,24 @@ const observer = new MutationObserver(() => { menu.prepend(pipButton); }); -global.togglePictureInPicture = () => { +global.togglePictureInPicture = async () => { + if (useNativePiP) { + const isInPiP = document.pictureInPictureElement !== null; + const video = $("video"); + const togglePiP = () => + isInPiP + ? document.exitPictureInPicture.call(document) + : video.requestPictureInPicture.call(video); + + try { + await togglePiP(); + $("#icon").click(); // Close the menu + return true; + } catch {} + } + ipcRenderer.send("picture-in-picture"); + return false; }; const listenForToggle = () => { @@ -75,19 +92,24 @@ const listenForToggle = () => { } function observeMenu(options) { + useNativePiP = options.useNativePiP; document.addEventListener( "apiLoaded", () => { - listenForToggle(); + if (!useNativePiP) { + listenForToggle(); + } // remove native listeners - cloneButton(".player-minimize-button").onclick = () => { - global.togglePictureInPicture(); - setTimeout(() => $('#player').click()); + cloneButton(".player-minimize-button").onclick = async () => { + const isUsingNativePiP = await global.togglePictureInPicture(); + if (!isUsingNativePiP) { + setTimeout(() => $("#player").click()); + } }; // allows easily closing the menu by programmatically clicking outside of it $("#expanding-menu").removeAttribute("no-cancel-on-outside-click"); - // TODO: think about wether an additional button in songMenu is needed + // TODO: think about wether an additional button in songMenu is needed observer.observe($("ytmusic-popup-container"), { childList: true, subtree: true,