Udemy.com Courses Auto-Enroll & Auto-Checkout

Instantly auto-clicks "Enroll now" on Udemy with coupons/discounts; shows popup banner at bottom-right before clicking button immediately.

// ==UserScript==
// @name         Udemy.com Courses Auto-Enroll & Auto-Checkout
// @namespace    https://www.linkedin.com/in/bernando-jr-minguita/
// @version      1.0
// @description  Instantly auto-clicks "Enroll now" on Udemy with coupons/discounts; shows popup banner at bottom-right before clicking button immediately.
// @author       Bernando Jr Minguita
// @match        https://www.udemy.com/course/*?*couponCode=*
// @match        https://www.udemy.com/payment/checkout/express/course/*?*discountCode=*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=udemy.com
// @grant        none
// @license      MIT
// ==/UserScript==

/*
MIT License

Copyright (c) 2025 Bernando Jr Minguita

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

(() => {
    'use strict';

    const OBSERVER_TIMEOUT_MS = 30000;

    function log(msg) {
        console.log(`[Udemy Auto-Enroll] ${msg}`);
    }

    function showBanner(message, bgColor = '#0073e6', timeout = 2000) {
        const banner = document.createElement('div');
        banner.textContent = message;

        banner.style.position = 'fixed';
        banner.style.top = '20px';
        banner.style.right = '20px';
        banner.style.padding = '12px 16px';
        banner.style.backgroundColor = bgColor;
        banner.style.color = '#fff';
        banner.style.fontSize = '14px';
        banner.style.fontWeight = 'bold';
        banner.style.fontFamily = 'Arial, sans-serif';
        banner.style.borderRadius = '6px';
        banner.style.boxShadow = '0 4px 10px rgba(0,0,0,0.2)';
        banner.style.zIndex = '999999';
        banner.style.maxWidth = '300px';
        banner.style.wordBreak = 'break-word';
        banner.style.opacity = '1';
        banner.style.transition = 'opacity 0.5s ease';

        document.body.appendChild(banner);

        setTimeout(() => {
            banner.style.opacity = '0';
            setTimeout(() => banner.remove(), 500); // Remove after fade-out
        }, timeout);
    }

    // ----------- Course page auto-enroll -----------

    function coursePageAutoEnroll() {
        let clicked = false;
        let observer = null;

        function disconnectObserver() {
            if (observer) {
                observer.disconnect();
                observer = null;
                log('MutationObserver disconnected.');
            }
        }

        function tryEnroll() {
            if (clicked) return;

            const pageText = document.body.textContent;

            if (pageText.includes('Buy now')) {
                log('Paid course detected. Stopping script.');
                disconnectObserver();
                return;
            }

            if (pageText.includes('You purchased this course on')) {
                log('Course already owned. Stopping script.');
                disconnectObserver();
                return;
            }

            if (!pageText.includes('Enroll now')) return;

            const enrollButton = document.querySelector('button[data-purpose="buy-this-course-button"]');
            if (enrollButton) {
                clicked = true;
                log('"Enroll now" button found. Clicking now.');
                showBanner('Auto-clicking "Enroll now" on this course...', '#0073e6');
                enrollButton.click();
                disconnectObserver();
            }
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', tryEnroll);
        } else {
            tryEnroll();
        }

        observer = new MutationObserver(() => tryEnroll());
        observer.observe(document.body, { childList: true, subtree: true });

        setTimeout(() => {
            disconnectObserver();
            log('Observer stopped after timeout.');
        }, OBSERVER_TIMEOUT_MS);
    }

    // ----------- Payment checkout auto-click -----------

    function paymentPageAutoCheckout() {
        let observer;

        function clickAndCleanup(button) {
            showBanner('Auto-clicking "Enroll now" on checkout...', '#d9534f');
            button.click();
            log('Checkout button clicked.');
            observer?.disconnect();
        }

        function attemptClick() {
            const xpath = `//button[contains(@class, 'checkout-button--checkout-button--button--') and .//span[text()='Enroll now']]`;
            const result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            const button = result.singleNodeValue;

            if (!button) {
                log('Checkout button not found. Waiting...');
                return;
            }

            if (button.disabled) {
                log('Checkout button found but disabled. Enabling manually.');
                button.disabled = false;
            }

            log('Checkout button found and enabled. Clicking now.');
            clickAndCleanup(button);
        }

        function initObserver() {
            observer = new MutationObserver(() => attemptClick());
            observer.observe(document.body, {
                childList: true,
                subtree: true,
                attributes: true
            });

            setTimeout(() => {
                observer?.disconnect();
                log('Observer stopped after timeout.');
            }, OBSERVER_TIMEOUT_MS);
        }

        log('Payment script active.');
        attemptClick();
        initObserver();
    }

    // ----------- Main Execution -----------

    const url = window.location.href;

    if (/^https:\/\/www\.udemy\.com\/course\/.+\?/.test(url) && url.includes('couponCode=')) {
        log('Detected Course page with couponCode. Running course auto-enroll.');
        coursePageAutoEnroll();
    } else if (/^https:\/\/www\.udemy\.com\/payment\/checkout\/express\/course\/.+\?/.test(url) && url.includes('discountCode=')) {
        log('Detected Payment checkout page with discountCode. Running payment auto-checkout.');
        paymentPageAutoCheckout();
    } else {
        log('No matching page detected. Script will not run.');
    }

})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址