YouTube PIP Button(iOS Safari)

Generate PIP button on YouTube Player

// ==UserScript==
// @name         YouTube PIP Button(iOS Safari)
// @version      1.0
// @description  Generate PIP button on YouTube Player
// @match        https://m.youtube.com/*
// @grant        none
// @namespace https://greasyfork.org/users/1405339
// ==/UserScript==

(function() {
    'use strict';

    const controlSelector = '.player-controls-bottom-left';

    function createPipButton(video) {
        const btn = document.createElement('button');
        btn.textContent = 'PIP';
        Object.assign(btn.style, {
            background: 'rgba(0,0,0,0)',
            color: '#f1f1f1',
            fontWeight: '500',
            padding: '12px 9px',
            fontSize: '17px',
            userSelect: 'none',
        });
        btn.classList.add('my-pip-btn');
        btn.onclick = e => {
            e.stopPropagation();
            if (!video) return;
            try {
                video.webkitPresentationMode === 'picture-in-picture' ?
                    video.webkitSetPresentationMode('inline') :
                    video.webkitSetPresentationMode('picture-in-picture');
            } catch {
            }
        };
        return btn;
    }

    function injectButtons() {
        const video = document.querySelector('video');
        if (!video) return;

        const roots = [document];
        const host = document.querySelector('ytp-player');
        if (host?.shadowRoot) roots.push(host.shadowRoot);

        roots.forEach(root => {
            root.querySelectorAll(controlSelector).forEach(container => {
                if (!container.querySelector('.my-pip-btn')) {
                    container.appendChild(createPipButton(video));
                }
            });
        });
    }

    new MutationObserver(injectButtons).observe(document.body, {childList: true, subtree: true});
    injectButtons();
})();