janisprefect / Twitch Safari PiP - Add Picture in Picture Button

// ==UserScript==
// @name         Twitch Safari PiP - Add Picture in Picture Button
// @namespace    janisprefect
// @version      0.1
// @description  Adds a button to the twitch player that enables Safari's picture in picture mode. It looks a bit odd, but it works
// @author       janisprefect
// @match        https://www.twitch.tv/*
// @grant        none
// @license     MIT
// ==/UserScript==

(function() {


    window.addEventListener('load',function() {

        var menu = document.querySelector('.player-buttons-right');
        var video = document.querySelector('.player-video video');

        // create pip button
        var button = document.createElement('button');
        button.classList.add('player-button','jvs-pip-button', 'pl-button__fullscreen--tooltip-left');

        var buttonInner = document.createElement('span');
        button.appendChild(buttonInner);

        var tooltip = document.createElement('span');
        tooltip.classList.add('player-tip');
        tooltip.setAttribute('data-tip','Picture in Picture');

        var icon = document.getElementById('icon_fullscreen').cloneNode(true);
        var iconContainer = document.createElement('span');
        iconContainer.appendChild(icon);

        buttonInner.appendChild(tooltip);
        buttonInner.appendChild(iconContainer);


        // add pip button to the menu
        if (menu) {
            console.log('adding pip button');
            menu.appendChild(button);

            // remove the right margin from the fullscreen button and add it to the pip button
            var fullscreenButton = document.querySelector('.qa-fullscreen-button');
            if (fullscreenButton) {
                fullscreenButton.classList.remove('pl-mg-r-1');
                button.classList.add('pl-mg-r-1');
            }

            // set click event to activate pip
            button.addEventListener('click',function() {
                console.log('switchting to pip mode');
                if (video) {
                    video.webkitSetPresentationMode('picture-in-picture');
                }
                else {
                    console.error("Can't switch to pip, video not found");
                }
            });
        }
        else {
            console.error("Could not add PiP Button, menu not found");
        }
    });
})();