我喜欢写的Greasemonkey / userscript自动添加.compact
与起始网址https://pay.reddit.com/因此它会自动重定向我的移动版本。
我一直在寻找类似的userscripts,尤其是这一个: https://userscripts.org/scripts/review/112568试图找出如何编辑替换模式,但我缺乏的技能在这个领域。
如何编写重定向我从一个Greasemonkey的脚本https://pay.reddit.com/*
到https://pay.reddit.com/*.compact
?
谢谢
这个脚本应该做这些事情:
- 检测如果当前URL已经到小型网站。
- 如有必要,加载页面的压缩版本。
- 谨防“锚” URL(他们最终以“碎片”或“哈希”(
#...
) ),并考虑他们。 - 请将不需要的网页进行浏览器历史记录中,这样的后退按钮效果很好。 只有
.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);
}
示例脚本显示你正在使用正则表达式来操作窗口的位置:
replace(/^https?:\/\/(www\.)?twitter.com/, 'https://mobile.twitter.com');
毫不奇怪,这取代了https://www.twitter.com
和http://twitter.com
等与https://mobile.twitter.com
。
你的情况略有不同,因为你想为一个字符串添加到您的网址,如果它的一些正则表达式匹配。 尝试:
var url = window.location.href;
var redditPattern = /^https:\/\/pay.reddit.com\/.*/;
// Edit: To prevent multiple redirects:
var compactPattern = /\.compact/;
if (redditPattern.test(url)
&& !compactPattern.test(url)) {
window.location.href = url + '.compact';
}
请参阅: http://jsfiddle.net/RichardTowers/4VjdZ/3测试用例。
文章来源: Add parameters to the URL (redirect) via a Greasemonkey/Tampermonkey/Userscript