YouTube Download Button (Bypass)

Hijacks the YouTube download button to send the video URL to Cobalt API.

// ==UserScript==
// @name         YouTube Download Button (Bypass)
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Hijacks the YouTube download button to send the video URL to Cobalt API.
// @author       ScriptDude777
// @license      GNU GPLv3
// @match        *://*.youtube.com/watch*
// @grant        GM.xmlHttpRequest
// ==/UserScript==

(function() {
    'use strict';

    function Cobalt(videoUrl) {
        return new Promise((resolve, reject) => {
            GM.xmlHttpRequest({
                method: 'POST',
                url: 'https://api.cobalt.tools/api/json',
                headers: {
                    'Cache-Control': 'no-cache',
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                },
                data: JSON.stringify({
                    url: encodeURI(videoUrl),
                    isAudioOnly: false,
                    vQuality: '1080', // modify this to change the quality
                    codec: 'avc1',
                    filenamePattern: 'basic',
                    disableMetadata: true,
                }),
                onload: (response) => {
                    const data = JSON.parse(response.responseText);
                    if (data?.url) resolve(data.url);
                    else reject(data);
                },
                onerror: (err) => reject(err),
            });
        });
    }

    function hijackDownloadButton() {
        const downloadButton = document.querySelector('ytd-download-button-renderer button');
        if (downloadButton) {
            downloadButton.onclick = async (event) => {
                event.preventDefault();

                const videoUrl = window.location.href;
                try {
                    const downloadUrl = await Cobalt(videoUrl);
                    console.log('Download link:', downloadUrl);
                    const link = document.createElement('a');
                    link.href = downloadUrl;
                    link.setAttribute('download', '');
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                } catch (err) {
                    console.error('Error fetching download URL:', err);
                    alert('Failed to fetch download link. Please try again.');
                }
            };
        }
    }

    const observer = new MutationObserver(mutations => {
        for (let mutation of mutations) {
            if (mutation.type === 'childList') {
                hijackDownloadButton();
                break;
            }
        }
    });

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

    hijackDownloadButton();
})();