Improve and enhance the script below to be more universally capable and to properly function as intended.


// ==UserScript==
// @name         Universal Media Downloader & Custom Video Player Injector fix
// @namespace    http://universal-media.com/
// @version      2.2
// @description  Inject a custom video player for media and provide download functionality for any detected video/audio on the page.
// @author       ChatGPT
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @run-at       document-end
// @require      https://cdn.plyr.io/3.6.8/plyr.polyfilled.js
/* global Plyr */
// ==/UserScript==

(() => {
    'use strict';

    // Inject custom styles for the player and download buttons
    GM_addStyle(`
        .download-button {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: #ff4500;
            color: white;
            padding: 5px 10px;
            font-size: 12px;
            border-radius: 5px;
            z-index: 9999;
            text-decoration: none;
            font-weight: bold;
        }
        .download-button:hover {
            background-color: #ff6347;
        }
        .plyr__video-embed {
            position: relative;
            padding-bottom: 56.25%;
            height: 0;
            overflow: hidden;
            max-width: 100%;
            background: #000;
        }
        .plyr__video-embed iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    `);

    // Helper function to inject the custom Plyr player for videos
    const injectCustomPlayer = (videoElement) => {
        const existingPlayer = videoElement.closest('.plyr');
        if (existingPlayer) {
            console.log('Player already injected for this element.');
            return;
        }

        // Create a wrapper for the video to ensure proper integration with Plyr
        const videoWrapper = document.createElement('div');
        videoWrapper.classList.add('plyr__video-wrapper');
        videoElement.parentNode.insertBefore(videoWrapper, videoElement);
        videoWrapper.appendChild(videoElement);

        // Initialize the Plyr player without assigning to a variable
        new Plyr(videoElement, {
            controls: ['play', 'progress', 'volume', 'fullscreen', 'download'],
        });

        // Custom download button integrated into the player UI
        const downloadButton = document.createElement('a');
        downloadButton.classList.add('download-button');
        downloadButton.innerText = 'Download';
        downloadButton.href = videoElement.currentSrc || videoElement.src;
        downloadButton.download = `video_${Date.now()}.mp4`;

        // Add the download button to the video container
        videoWrapper.appendChild(downloadButton);

        console.log('Custom player injected with download functionality.');
    };

    // Function to detect media elements and inject the player
    const detectAndInjectPlayers = () => {
        const mediaElements = document.querySelectorAll('video');
        mediaElements.forEach((mediaElement) => {
            injectCustomPlayer(mediaElement);
        });
    };

    // Function to observe the DOM for new media elements and inject players dynamically
    const observeMediaChanges = () => {
        const mediaObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.tagName === 'VIDEO') {
                        injectCustomPlayer(node);
                    } else if (node.querySelectorAll) {
                        node.querySelectorAll('video').forEach(injectCustomPlayer);
                    }
                });
            });
        });

        mediaObserver.observe(document.body, {
            childList: true,
            subtree: true,
        });
    };

    // Main initialization function
    const initialize = () => {
        detectAndInjectPlayers(); // Detect any video elements already present
        observeMediaChanges(); // Observe and handle dynamic media elements
    };

    // Initialize the script when the page has fully loaded
    window.addEventListener('load', initialize);
})();