通过Greasemonkey / Tampermonkey / Userscript将参数添加到URL(重定向)

nod*_*scc 4 url redirect greasemonkey userscripts tampermonkey

我想编写一个Greasemonkey /用户脚本,该脚本会自动添加.compact到以https://pay.reddit.com/开头的URL,因此它会自动将我重定向到移动版本。

我一直在寻找类似的用户脚本,尤其是以下用户脚本:https ://userscripts.org/scripts/review/112568 试图弄清楚如何编辑替换模式,但是我在这一领域缺乏技能。

如何编写将我从重定向https://pay.reddit.com/*到的Greasemonkey脚本https://pay.reddit.com/*.compact

谢谢

Bro*_*ams 6

该脚本应执行以下操作:

  1. 检测当前URL是否已到达压缩站点。
  2. 如有必要,加载页面的精简版。
  3. 当心“锚定” URL(以“碎片”或“哈希”(#...结尾)并说明它们。
  4. 将不需要的页面放在浏览器历史记录之外,以便“后退”按钮正常工作。只.compact记住URL。
  5. 通过在运行document-start,脚本在这种情况下可以提供更好的性能。

为此,此脚本有效:

// ==UserScript==
// @name        _Reddit, ensure compact site is used
// @match       *://*.reddit.com/*
// @run-at      document-start
// @grant       none
// ==/UserScript==

var oldUrlPath  = window.location.pathname;

/*--- Test that ".compact" is at end of URL, excepting any "hashes"
    or searches.
*/
if ( ! /\.compact$/.test (oldUrlPath) ) {

    var newURL  = window.location.protocol + "//"
                + window.location.host
                + oldUrlPath + ".compact"
                + window.location.search
                + window.location.hash
                ;
    /*-- replace() puts the good page in the history instead of the
        bad page.
    */
    window.location.replace (newURL);
}
Run Code Online (Sandbox Code Playgroud)