Greasemonkey/Tampermonkey script to redirect to doubly modified URL

ぐ巨炮叔叔 提交于 2019-12-23 01:01:18

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/49658374/greasemonkey-tampermonkey-script-to-redirect-to-doubly-modified-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!