Greasemonkey/Tampermonkey 脚本重定向到双重修改的 URL

rjm*_*a13 3 javascript url greasemonkey userscripts tampermonkey

目标页面的 URL 为:   ouo.io/tLnpEc.html

我想将网址更改为:ouo.press/tLnpEc

即:.ioto.press和remove .html

我已经有了这个,但它不起作用(它重定向到 ouo.press 但仍然没有删除 .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);
}
Run Code Online (Sandbox Code Playgroud)

我希望有人可以帮助解决这个问题。

Bro*_*ams 6

相关:Greasemonkey 将网站 URL 从 .html 重定向到 -print.html?(以及其他几个)。

关键点:

  1. 检查页面位置以确保您尚未重定向;以避免无限重定向循环。
  2. 不要在 上进行操作.href。这会对各种引用、搜索等链接和重定向产生副作用和错误触发。
  3. 用于@run-at document-start减少延迟和烦人的“闪烁”。

下面是执行这些 URL 更改和重定向的完整脚本:

// ==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);
}
Run Code Online (Sandbox Code Playgroud)