Greasy Fork

Greasy Fork is available in English.

super fast load

Stop YouTube autoplay•Add download button under videos•Block ads, pop-ups, trackers•Speed up slow browsing•Save data on low-speed internet•Preload links for fast clicks•Hide cookie banners•Disable location tracking•Block unneeded scripts•Optimize for VPN/Tor•Lazy load images/videos•Remove tracking/ads scripts•Boost download connections

目前为 2024-12-18 提交的版本。查看 最新版本

// ==UserScript==
// @name         super fast load
// @namespace    http://tampermonkey.net/
// @version      2
// @description  Stop YouTube autoplay•Add download button under videos•Block ads, pop-ups, trackers•Speed up slow browsing•Save data on low-speed internet•Preload links for fast clicks•Hide cookie banners•Disable location tracking•Block unneeded scripts•Optimize for VPN/Tor•Lazy load images/videos•Remove tracking/ads scripts•Boost download connections
// @author       farzan farhangi
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// @require      https://cdn.jsdelivr.net/npm/[email protected]/umd/browser/brotli.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/zstd/1.3.8/zstd.min.js
// @connect      * // این خط برای جلوگیری از پیغام دسترسی به منابع بین‌مرزی است
// ==/UserScript==

(function() {
    'use strict';

    const CONFIG = {
        resourceCache: new Map(),
        optimizationUrls: ['https://example1.com/resource.js', 'https://example2.com/styles.css'],
        blockList: ['ads.example.com', 'tracking.example.com'],
        nonEssentialSelectors: ['script[src*="tracking"]', 'iframe[src*="advertisement"]', '.ad-banner', '.cookie-consent'],
        criticalResources: ['https://example.com/styles.css', 'https://example.com/script.js'],
        concurrentConnections: 8,
        timeout: 500,
    };

    // Function to continuously monitor connection status
    const monitorConnection = async () => {
        while (true) {
            try {
                const response = await fetch('https://www.google.com/generate_204', { method: 'GET', mode: 'no-cors' });
                if (response.status >= 200 && response.status < 300) {
                    console.log("Internet is stable.");
                } else {
                    throw new Error("Connectivity issue detected.");
                }
            } catch (error) {
                console.warn("Internet connection lost! Attempting to reconnect...");
                reconnectNetwork();
            }
            await new Promise(resolve => setTimeout(resolve, 3000)); // Check every 3 seconds
        }
    };

    // Advanced reconnection function
    const reconnectNetwork = async () => {
        console.log("Reconnecting to the network...");
        try {
            await clearDNSCache();
            console.log("DNS cache cleared.");
            navigator.serviceWorker.getRegistrations().then(registrations => {
                registrations.forEach(reg => reg.unregister());
                console.log("Service workers reset.");
            });
            if (navigator.connection && navigator.connection.type) {
                navigator.connection.type = "wifi";
                console.log("Network interface reinitialized.");
            }
            console.log("Reconnection attempt completed.");
        } catch (error) {
            console.error("Error during reconnection process:", error);
        }
    };

    // Clear DNS cache function
    const clearDNSCache = async () => {
        try {
            await Promise.all([
                fetch('https://1.1.1.1/generate_204', { method: 'GET', mode: 'no-cors' }),
                fetch('https://8.8.8.8/generate_204', { method: 'GET', mode: 'no-cors' }),
            ]);
            console.log("DNS cache refreshed.");
        } catch (error) {
            console.warn("Failed to refresh DNS cache:", error);
        }
    };

    // Retry logic for all network requests
    const enhanceRequestStability = () => {
        const originalFetch = window.fetch;
        window.fetch = async (...args) => {
            for (let attempt = 1; attempt <= 5; attempt++) {
                try {
                    const response = await originalFetch(...args);
                    if (response.ok) return response;
                } catch (error) {
                    console.warn(`Fetch attempt ${attempt} failed. Retrying...`, error);
                }
                await new Promise(resolve => setTimeout(resolve, 2000)); // Delay between retries
            }
            console.error("Fetch failed after 5 retries.");
            throw new Error("Failed to stabilize request.");
        };

        const originalXMLHttpRequest = window.XMLHttpRequest;
        window.XMLHttpRequest = function() {
            const xhr = new originalXMLHttpRequest();
            xhr.addEventListener("error", () => {
                console.warn("XHR failed. Retrying...");
                setTimeout(() => xhr.open(xhr.method, xhr.url, true), 2000); // Retry with delay
            });
            return xhr;
        };
    };

    class Utilities {
        static async fetchWithTimeout(url, options = {}) {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), CONFIG.timeout);
            try {
                const response = await fetch(url, { ...options, signal: controller.signal });
                clearTimeout(timeoutId);
                return response;
            } catch (error) {
                clearTimeout(timeoutId);
                throw error;
            }
        }

        static injectCSS(css) {
            const style = document.createElement('style');
            style.textContent = css;
            document.head.appendChild(style);
        }

        static preloadLinks() {
            const links = document.querySelectorAll('a[href]');
            links.forEach(link => {
                if (!CONFIG.resourceCache.has(link.href)) {
                    const linkElement = document.createElement('link');
                    linkElement.rel = 'prefetch';
                    linkElement.href = link.href;
                    document.head.appendChild(linkElement);
                    CONFIG.resourceCache.set(link.href, true);
                }
            });
        }

        static async compressData(data) {
            return new Uint8Array(await brotli.compress(new TextEncoder().encode(data)));
        }

        static async decompressData(data) {
            return new TextDecoder().decode(await brotli.decompress(data));
        }
    }

    class ResourceManager {
        static async loadWithMultipleConnections(url) {
            if (CONFIG.resourceCache.has(url)) return CONFIG.resourceCache.get(url);
            try {
                const response = await Utilities.fetchWithTimeout(url, { cache: 'force-cache', mode: 'no-cors' });
                if (!response.ok) throw new Error('Network response was not ok');
                const text = await response.text();
                const compressed = await Utilities.compressData(text);
                CONFIG.resourceCache.set(url, compressed);
                return compressed;
            } catch (error) {
                console.error('Download error:', error);
                return null;
            }
        }

        static async loadResource(url, type) {
            const compressed = await this.loadWithMultipleConnections(url);
            if (!compressed) return;
            const decompressed = await Utilities.decompressData(compressed);
            const blob = new Blob([decompressed], { type: type === 'css' ? 'text/css' : 'application/javascript' });
            const blobUrl = URL.createObjectURL(blob);
            const element = document.createElement(type === 'css' ? 'link' : 'script');
            element[type === 'css' ? 'href' : 'src'] = blobUrl;
            element.rel = type === 'css' ? 'stylesheet' : undefined;
            element.defer = type !== 'css';
            document.head.appendChild(element);
        }

        static preloadResources() {
            const resources = [...CONFIG.criticalResources, ...CONFIG.optimizationUrls];
            resources.forEach(resource => {
                this.loadResource(resource, resource.endsWith('.css') ? 'css' : 'js');
            });
        }
    }

    class SecurityEnhancer {
        static blockUnnecessaryRequests() {
            const originalOpen = XMLHttpRequest.prototype.open;
            XMLHttpRequest.prototype.open = function(method, url, ...args) {
                if (CONFIG.blockList.some(domain => url.includes(domain))) {
                    console.log(`Blocked request to: ${url}`);
                    return;
                }
                return originalOpen.call(this, method, url, ...args);
            };
        }

        static preventDataCollection() {
            navigator.geolocation.getCurrentPosition = () => console.warn("Geolocation access blocked.");
            Object.defineProperty(navigator, 'userAgent', { get: () => 'Blocked User Agent' });
        }

        static removeNonEssentialElements() {
            CONFIG.nonEssentialSelectors.forEach(selector => {
                document.querySelectorAll(selector).forEach(element => element.remove());
            });
        }
    }

    class MediaOptimizer {
        static preventAutoplay() {
            const stopAutoplay = (media) => {
                media.pause();
                media.preload = 'none';
                media.autoplay = false;
                media.setAttribute('data-autoplay-prevented', 'true');

                media.addEventListener('click', () => {
                    if (media.paused) {
                        media.play();
                    } else {
                        media.pause();
                    }
                });

                media.controls = false;

                const playButton = media.closest('.ytp-large-play-button, .ytp-small-play-button');
                if (playButton) {
                    playButton.style.display = 'none';
                }
            };

            document.querySelectorAll('video, audio').forEach(stopAutoplay);

            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.type === 'childList') {
                        mutation.addedNodes.forEach((node) => {
                            if (node.nodeName === 'VIDEO' || node.nodeName === 'AUDIO') {
                                stopAutoplay(node);
                            } else if (node.querySelectorAll) {
                                node.querySelectorAll('video, audio').forEach(stopAutoplay);
                            }
                        });
                    }
                });
            });

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

        static lazyLoadMedia() {
            const observer = new IntersectionObserver(entries => {
                entries.forEach(async entry => {
                    if (entry.isIntersecting) {
                        const media = entry.target;
                        const compressed = await ResourceManager.loadWithMultipleConnections(media.dataset.src);
                        if (compressed) {
                            const decompressed = await Utilities.decompressData(compressed);
                            const blob = new Blob([decompressed]);
                            media.src = URL.createObjectURL(blob);
                            observer.unobserve(media);
                        }
                    }
                });
            }, { threshold: 0.1, rootMargin: '200px' });

            document.querySelectorAll('video[data-src], audio[data-src], img[data-src]').forEach(media => observer.observe(media));
        }

        static enableLazyLoadImages() {
            document.querySelectorAll('img:not([loading])').forEach(img => {
                img.loading = 'lazy';
                img.decoding = 'async';
                img.referrerPolicy = 'no-referrer';
            });
        }
    }

    class YouTubeEnhancer {
        static createDownloadButton() {
            const downloadButton = document.createElement('button');
            downloadButton.id = 'custom-download-button';
            downloadButton.textContent = 'VIDEO DOWNLOAD';
            downloadButton.onclick = this.showModal;

            const interval = setInterval(() => {
                const controls = document.querySelector('.ytp-right-controls');
                if (controls && !document.getElementById('custom-download-button')) {
                    controls.insertBefore(downloadButton, controls.firstChild);
                    clearInterval(interval);
                }
            }, 1000);
        }

        static showModal() {
            const overlay = document.createElement('div');
            overlay.id = 'modal-overlay';
            overlay.onclick = YouTubeEnhancer.hideModal;

            const modalContent = document.createElement('div');
            modalContent.id = 'modal-content';

            const iframe = document.createElement('iframe');
            const videoID = new URLSearchParams(window.location.search).get('v');
            if (videoID) {
                iframe.src = `https://www.y2mate.com/youtube/${videoID}`;
            }
            modalContent.appendChild(iframe);
            overlay.appendChild(modalContent);
            document.body.appendChild(overlay);

            overlay.style.display = 'flex';
        }

        static hideModal() {
            document.getElementById('modal-overlay')?.remove();
        }
    }

    function optimizePerformance() {
        SecurityEnhancer.blockUnnecessaryRequests();
        SecurityEnhancer.preventDataCollection();
        MediaOptimizer.lazyLoadMedia();
        MediaOptimizer.enableLazyLoadImages();
        SecurityEnhancer.removeNonEssentialElements();
        Utilities.preloadLinks();
    }

    Utilities.injectCSS(`
        #custom-download-button {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #3399ff;
            color: white;
            border: none;
            padding: 10px 28px;
            border-radius: 25px;
            font-size: 14px;
            cursor: pointer;
            z-index: 1000;
        }

        #modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 2000;
        }

        #modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 600px;
        }

        #modal-content iframe {
            width: 100%;
            height: 400px;
            border: none;
        }

        .ytp-large-play-button, .ytp-small-play-button {
            display: none !important;
        }

        video::-webkit-media-controls {
            display: none !important;
        }
    `);

    ResourceManager.preloadResources();

    window.addEventListener('yt-navigate-finish', () => {
        MediaOptimizer.preventAutoplay();
        YouTubeEnhancer.createDownloadButton();
    });

    window.addEventListener('load', () => {
        MediaOptimizer.preventAutoplay();
        YouTubeEnhancer.createDownloadButton();
        optimizePerformance();
    });

    const originalPushState = history.pushState;
    history.pushState = function() {
        originalPushState.apply(this, arguments);
        MediaOptimizer.preventAutoplay();
    };

    const originalReplaceState = history.replaceState;
    history.replaceState = function() {
        originalReplaceState.apply(this, arguments);
        MediaOptimizer.preventAutoplay();
    };

    // Immediate execution of critical optimizations
    (async () => {
        await ResourceManager.preloadResources();
        SecurityEnhancer.blockUnnecessaryRequests();
        SecurityEnhancer.preventDataCollection();
        MediaOptimizer.preventAutoplay();
    })();

    // Start monitoring connection
    monitorConnection();
    enhanceRequestStability();

    console.log("Combined Internet Optimizer and Downloader is active.");
})();