Greasy Fork

Greasy Fork is available in English.

縮減蝦皮網址

網址只留下識別碼

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

// ==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.2.1
// ==/UserScript==

(function() {
    'use strict';

    // 定義正規表達式,用於提取 shopId 和 itemId
    const shopeeRegex = /shopee\.tw\/(?:.*-i\.(\d+)\.(\d+)|.*deals\/(\d+)\/.*\/(\d+))/;
    let lastHandledUrl = '';

    // 處理網址縮短的核心函式
    function processUrl() {
        const currentUrl = window.location.href;

        // 如果目前的網址和上次處理的網址相同,就不用再處理了
        if (currentUrl === lastHandledUrl) {
            return;
        }

        const match = currentUrl.match(shopeeRegex);

        if (match) {
            let shopId, itemId, newUrl;

            // 根據匹配結果判斷網址類型
            if (match[1] && match[2]) {
                // 這是舊的商品網址格式
                shopId = match[1];
                itemId = match[2];
            } else if (match[3] && match[4]) {
                // 這是新的加購價網址格式
                shopId = match[3];
                itemId = match[4];
            }

            // 檢查是否成功提取到 shopId 和 itemId
            if (shopId && itemId) {
                newUrl = `https://shopee.tw/0-i.${shopId}.${itemId}`;

                // 如果目前的網址已經是精簡格式,就跳過
                if (currentUrl === newUrl) {
                    return;
                }

                // 使用 history.replaceState() 來修改網址
                window.history.replaceState({}, '', newUrl);

                // 更新上次處理的網址
                lastHandledUrl = newUrl;

                console.log("網址已縮短為:", newUrl);
            }
        }
    }

    // 每 200 毫秒執行一次 processUrl 函式
    // 這是一個折衷方案,既能確保即時性,又不會對效能造成太大影響
    setInterval(processUrl, 200);

    // 確保頁面剛載入時也能處理,手動呼叫一次
    window.addEventListener('load', processUrl);

})();