我想编写一个 Greasemonkey/userscript,自动将 .compact
添加到以 https://pay.reddit.com/ 开头的 URL所以它会自动将我重定向到移动版本。
我一直在寻找类似的用户脚本,特别是这个:https://userscripts.org/scripts/review/112568试图弄清楚如何编辑替换模式,但我缺乏这方面的技能。
如何编写一个 Greasemonkey 脚本,将我从 https://pay.reddit.com/*
重定向到 https://pay.reddit.com/*.compact
?
谢谢
最佳答案
脚本应该做这些事情:
- 检测当前 URL 是否已指向紧凑站点。
- 如有必要,加载页面的精简版本。
- 谨防“锚定”网址(以 "fragments" or "hashes" (
#...
) 结尾)并加以考虑。 - 将不需要的页面从浏览器历史记录中删除,以便后退按钮正常工作。只会记住
.compact
URL。 - 通过在
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/