Greasy Fork

Greasy Fork is available in English.

縮減蝦皮網址

網址只留下識別碼

当前为 2025-09-16 提交的版本,查看 最新版本

// ==UserScript==
// @name        縮減蝦皮網址
// @namespace   http://greasyfork.icu/zh-TW/scripts/457084
// @match       *shopee.tw/*
// @author      czh
// @icon        https://www.google.com/s2/favicons?sz=64&domain=shopee.tw
// @run-at      document-start
// @license     GNU GPLv3
// @description 網址只留下識別碼
// @version 0.0.1.8
// ==/UserScript==

(function() {
    'use strict';

    // 定義一個正規表達式來匹配蝦皮商品的網址
    const shopeeRegex = /shopee\.tw\/.*-i\.(\d+)\.(\d+)/;

    // 建立一個函式來處理網址縮短的邏輯
    function shortenShopeeUrl() {
        const originalUrl = window.location.href;
        const match = originalUrl.match(shopeeRegex);

        // 如果匹配成功
        if (match) {
            const shopId = match[1];
            const itemId = match[2];

            // 構建新的精簡網址,使用 '0' 作為商品標題的佔位符
            const newUrl = `https://shopee.tw/0-i.${shopId}.${itemId}`;

            // 如果目前的網址和精簡後的網址不完全相同,才進行替換
            if (originalUrl !== newUrl) {
                window.history.pushState({}, '', newUrl);
                console.log("網址已縮短為:", newUrl);
            }
        }
    }

    // 當頁面完全載入後執行一次縮短函式
    window.addEventListener('load', shortenShopeeUrl);

    // 監聽網址列的變化(當使用者點擊頁面內的連結時)
    // 這是一個強大的功能,可以捕捉動態載入的新網址
    window.addEventListener('popstate', shortenShopeeUrl);

    // 針對頁面載入後,網址可能動態變化的情況,我們再多加一個 MutationObserver
    // 雖然 popstate 通常就夠了,但多一層防護總是好的
    const observer = new MutationObserver(shortenShopeeUrl);
    observer.observe(document.body, { childList: true, subtree: true });

})();