Remove URL Tracking Parameters

移除網址中的跟踪參數

目前為 2024-08-17 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Remove URL Tracking Parameters
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  移除網址中的跟踪參數
// @author abc0922001
// @match        *://*/*
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    // 使用 Set 來存儲跟踪參數
    const trackingParams = new Set([
        'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 
        'fbclid', 'gclid', 'yclid', 'mc_cid', 'mc_eid', 'dclid'
    ]);

    function removeTrackingParams(url) {
        try {
            const urlObj = new URL(url);
            let params = urlObj.searchParams;
            let removed = false;

            trackingParams.forEach(param => {
                if (params.has(param)) {
                    params.delete(param);
                    removed = true;
                }
            });

            return removed ? urlObj.toString() : url;
        } catch (error) {
            console.error('Error processing URL:', error);
            return url;
        }
    }

    function cleanURL() {
        const currentUrl = window.location.href;
        const cleanedUrl = removeTrackingParams(currentUrl);
        
        if (cleanedUrl !== currentUrl) {
            try {
                window.history.replaceState({}, document.title, cleanedUrl);
            } catch (error) {
                console.error('Error updating URL:', error);
            }
        }
    }

    // 初始清理
    cleanURL();

    // 監聽 URL 變化
    window.addEventListener('popstate', cleanURL);

    // 對於單頁應用,可以考慮額外監聽自定義事件
    // 例如:window.addEventListener('routechange', cleanURL);
})();