试图通过 tampermonkey 将 www.youtube.com 重定向到 www.nsfwyoutube.com

trying to redirect www.youtube.com to www.nsfwyoutube.com Via tampermonkey

正如标题所说,

我一直在尝试使用以下代码重定向 youtube url:

// ==UserScript==
// @run-at document-start
// @name        youtube to nsfwyoutube
// @include     https://www.youtube.com/*
// @exclude     https://www.youtube.com
// @exclude     https://www.youtube.com/feed*
// @exclude     https://www.youtube.com/channel*
// @exclude     https://www.youtube.com/results*
// @exclude     https://www.youtube.com/c*
// @version     1
// @grant       none
// ==/UserScript==

var oldUrlPath = window.location.host + "/" + window.location.pathname;

/*--- Test that ".compact" is at end of URL, excepting any "hashes"
    or searches.
*/
if ( ("www.nsfwyoutube.com/watch") != oldUrlPath) {

    var newURL = window.location.protocol + "//"
    + "www.nsfwyoutube.com"
    + "/watch"
    + window.location.search
    + window.location.hash
    ;
    /*-- replace() puts the good page in the history instead of the
        bad page.
    */
    window.location.replace (newURL);
}

开始看视频好像不行,我代码不是很好

我正在使用 firefox。

您的 if 条件没有用,因为 tampermonkey 脚本只会在匹配 @include@exclude 规则时执行。

window.location.pathname 在您创建 newURL 时丢失了。您可以在浏览器控制台中获得 window.location.xxx 的结果。

// ==UserScript==
// @name        youtube to nsfwyoutube
// @include     https://www.youtube.com/*
// @exclude     https://www.youtube.com
// @exclude     https://www.youtube.com/feed*
// @exclude     https://www.youtube.com/channel*
// @exclude     https://www.youtube.com/results*
// @exclude     https://www.youtube.com/c*
// @run-at      document-start
// @version     1
// @grant       none
// ==/UserScript==

var newHost = window.location.host.replace("youtube", "nsfwyoutube");

var newURL = window.location.protocol + "//" +
             newHost +
             window.location.pathname +
             window.location.search +
             window.location.hash;

window.location.replace (newURL);

看来你只希望在打开视频时执行脚本,所以你可以将header更改为

// ==UserScript==
// @name        youtube to nsfwyoutube
// @match       *://*youtube.com/watch*
// @run-at      document-start
// @version     1
// @grant       none
// ==/UserScript==

可以在 https://www.tampermonkey.net/documentation.php 找到 tampermonkey 的文档。