Skip to content

Custom Handlers

Kain edited this page Mar 13, 2024 · 2 revisions

Custom Handlers

These are rules by websites that can't be processed normally. Instead, they need their own handler (A chunk of code made just for that URL).

One of the easiest examples is from click.redditmail.com that tracks what you click in the emails you're sent.

The handler for this domain is as follows:

handlers['click.redditmail.com'] = {
    note: 'Reddit evil.',
    exec: (str, args) => {
        try {
            const reg = /https:\/\/click\.redditmail\.com\/CL0\/(.*?)\//gi;
            const matches = regexExtract(reg, str);

            if (typeof matches[1] === 'undefined') throw Error('regexExtract failed to find a URL');
            const url = decodeURIComponent(matches[1]);

            return { url: url };
        } catch (error) {
            return { url: args.originalURL, error };
        }
    }
};

The handlers is an object that uses a domain as a key. This object has two main properties: note and exec. The note is optional and doesn't have an effect on the code in any way, it's simply there to let the reader know something important about the handler.

The exec function is passed two parameters. str is the original URL. You're welcome to modify this value as much as you need.
The other parameter is args, this is an object that contains a bunch of useful information for each rule.

interface IHandlerArgs {
    /** The attempt made at decoding the string, may be invalid */
    decoded: string;
    /** The last part of the URL path, split by a forward slash */
    lastPath: string;
    /** The full URL path excluding the host */
    fullPath: string;
    /** A fresh copy of URLSearchParams */
    urlParams: URLSearchParams;
    /** The original URL */
    readonly originalURL: string;
}

Once the handler code is created you can make a rule that uses it:

{
    name: 'click.redditmail.com',
    match: /click.redditmail.com/i,
    decode: { handler: 'click.redditmail.com' }
}

And you're done. The result is as follows:

Input: (276 characters)

https://click.redditmail.com/CL0/https:%2F%2Fwww.reddit.com%2Fr%2Ftypescript%2F%3Fref=admin_announcement_email&ref_campaign=admin_announcement_email&ref_source=email/1/0100018dc9fb8341-06e5c333-a26d-4901-b75a-4b34820622a2-000000/ieA1a6ILAddsa9lHdNyVoGFdsaReMXiVKoZPVr9nX7w=341

Result: (36 characters)

https://www.reddit.com/r/typescript/

It's worth mentioning that if you have allowReclean set to false you will receive a URL with some other tracking parameters in it, you can see these in the original URL. I recommend leaving it on true.

This one is 120 characters, still an improvement even without the re-clean.

https://www.reddit.com/r/typescript/?ref=admin_announcement_email&ref_campaign=admin_announcement_email&ref_source=email
Clone this wiki locally