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

标签 url redirect greasemonkey tampermonkey userscripts

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

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

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

谢谢

最佳答案

脚本应该做这些事情:

  1. 检测当前 URL 是否已指向紧凑站点。
  2. 如有必要,加载页面的精简版本。
  3. 谨防“锚定”网址(以 "fragments" or "hashes" (#...) 结尾)并加以考虑。
  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);
}

关于url - 通过 Greasemonkey/Tampermonkey/Userscript 将参数添加到 URL(重定向),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10675049/

相关文章:

javascript - 如何在用户脚本中鼠标悬停时获取图像的 src

python - 使用正则表达式从 url 中提取子路径

javascript - 使用正则表达式进行 jQuery Youtube URL 验证

c# - 在哪里放置代码以将用户重定向回页面直到谓词为真?

javascript - 通过任何方法重定向到新选项卡。 (JS、Symfony PHP 组件等)

ruby-on-rails - 重定向后的验证消息

javascript - Tampermonkey,等待在另一个选项卡操作系统中设置可以读取的值

php - 这个 javascript 代码是什么意思以及如何使用 php 对其进行解码

ios - UIWebview 加载时可以更改 URL 吗? (iOS)

javascript - 匹配多行模式