Daraz Clean URL Shortener

Cleans Daraz product URLs everywhere: link hrefs, on click, and even in the address bar after loading the page.

2025-06-02 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

// ==UserScript==
// @name         Daraz Clean URL Shortener
// @namespace    Violent Monkey Script
// @version      1.0.2
// @description  Cleans Daraz product URLs everywhere: link hrefs, on click, and even in the address bar after loading the page.
// @author       Grizz1e
// @match        *://www.daraz.com.np/*
// @grant        none
// @license      GPL-3.0-or-later
// ==/UserScript==

(function () {
    'use strict';

    const productUrlRegex = /^https:\/\/www\.daraz\.com\.np\/products\/(?:[^\/]+-)?(i\d+-s\d+)\.html(?:\?.*)?$/;

    function getCleanDarazUrl(url) {
        const match = url.match(productUrlRegex);
        return match ? `https://www.daraz.com.np/products/${match[1]}.html` : null;
    }

    function rewriteAllLinks() {
        const links = document.querySelectorAll('a[href*="daraz.com.np/products/"]');
        links.forEach(link => {
            const cleanUrl = getCleanDarazUrl(link.href);
            if (cleanUrl) {
                link.href = cleanUrl;
            }
        });
    }

    function interceptClickEvents() {
        document.addEventListener('click', function (e) {
            const link = e.target.closest('a[href*="daraz.com.np/products/"]');
            if (link) {
                const cleanUrl = getCleanDarazUrl(link.href);
                if (cleanUrl && link.href !== cleanUrl) {
                    e.preventDefault();
                    window.location.href = cleanUrl;
                }
            }
        }, true);
    }

    function cleanAddressBar() {
        const currentUrl = window.location.href;
        const cleanUrl = getCleanDarazUrl(currentUrl);
        if (cleanUrl && currentUrl !== cleanUrl) {
            history.replaceState(null, '', cleanUrl); // clean address bar without reload
        }
    }

    // Run on page load
    rewriteAllLinks();
    interceptClickEvents();
    cleanAddressBar();

    // Watch for dynamic content
    const observer = new MutationObserver(() => {
        rewriteAllLinks();
    });
    observer.observe(document.body, { childList: true, subtree: true });
})();