rjmolina13
rjmolina13

Reputation: 33

Greasemonkey/Tampermonkey script to redirect to doubly modified URL

The target page has the URL:   ouo.io/tLnpEc.html

And I want to change the URL to: ouo.press/tLnpEc

That is: .io to .press and remove .html.

I already have this but it ain't working (It redirects to ouo.press but still doesn't remove .html):

var url = window.location.host;

if (url.match("//ouo.io") === null) {
    url = window.location.href;
    if  (url.match("//ouo.io") !== null){
        url = url.replace("//ouo.io", "//ouo.press");
    } else if (url.match("/*.html") !== null){
        url = url.replace("/*.html", " ");
    } else {
        return;
    }
    console.log(url);
    window.location.replace(url);
}

I hope someone can help on this problem.

Upvotes: 3

Views: 11590

Answers (1)

Brock Adams
Brock Adams

Reputation: 93473

Related: Greasemonkey to redirect site URLs from .html to -print.html? (and several others).

Key points:

  1. Check the page location to make sure you haven't already redirected; to avoid an infinite redirect loop.
  2. Don't operate on .href. This will cause side effects and false triggers for various referer, search, etc. links and redirects.
  3. Use @run-at document-start to reduce delays and annoying "blinks".

Here's a complete script that performs those URL changes and redirects:

// ==UserScript==
// @name     _Redirecy ouo.io/...html files to ouo.press/... {plain path}
// @match    *://ouo.io/*
// @run-at   document-start
// @grant    none
// ==/UserScript==

//-- Only redirect if the *path* ends in .html...
if (/\.html$/.test (location.pathname) ) {
    var newHost     = location.host.replace (/\.io$/, ".press");
    var plainPath   = location.pathname.replace (/\.html$/, "");
    var newURL      = location.protocol + "//" +
        newHost                  +
        plainPath                +
        location.search          +
        location.hash
    ;
    location.replace (newURL);
}

Upvotes: 7

Related Questions