Search code examples
greasemonkeytampermonkey

Use Greasemonkey to change URL links within a given domain


I'm new to Greasemonkey (Tampermonkey actually), and I'd like to write a very short script that:

  • Is valid within a given domain (e.g. "mydomain.com")

  • Parses all button-related URL links within the active tab

  • Replaces them as follows :

    Original URL link: [string_1]/[useful_part]?[string_2]

    To be replaced with: [replacement_1]/[useful_part]

    So everything after the "?" can be discarded, including the "?" itself.

More specifically, URL links are as follows:

http://127.0.0.1:6878/webui/player/[useful_part]?autoplay=true

So string 1 = "http://127.0.0.1:6878/webui/player" and string 2 = "autoplay=true"

I've seen a similar question here: Rewrite parts of links using Greasemonkey and FireFox

But I'm not good enough at RegEx, so I couldn't adapt the script to my own needs.

I've also looked for Firefox extensions, but the available extensions don't seem to allow the level of text replacement that I'm seeking.


Solution

  • Here is the working script thanks to cssyphus. {DOMAIN_NAME} needs of course to be replaced:

    // ==UserScript==
    // @name         Webui Player Replacements
    // @namespace    http://tampermonkey.net/
    // @description  Change URL links to AceStream on a given domain
    // @version      0.1
    // @match        http://{DOMAIN_NAME}/*
    // @grant        none
    // ==/UserScript==
    
    (function() {
        'use strict';
        const lnks = document.querySelectorAll('a');
        lnks.forEach( (el) => {
            const href = el.getAttribute('href');
            const ed1 = href.split('?')[0];
            const ed2 = ed1.replace('http://127.0.0.1:6878/webui/player/','');
            el.setAttribute('href', `acestream://${ed2}`);
            el.setAttribute('onclick', `event.preventDefault();window.open('acestream://${ed2}')`);
        });
    })();