当我单击书签时,如何创建一个用其他内容替换部分 URL 的脚本?

How do I create a script that replaces part of the URL with something else when I click a bookmark?

我想知道如何创建一个脚本来替换“https://www”。在 Reddit URL 中,当我单击书签时使用 "ps."。有谁知道我该怎么做?我的编程知识非常有限。

你在说什么"bookmarklet"。

在Chrome中打开书签栏。右键单击它,按 "Add page",为其命名,然后作为值(而不是 URL)粘贴到 javascript 函数,例如像这样(取自crossbrowsertesting.com):

javascript:(function(){if(typeof cbt_script=='undefined'){cbt_script=document.createElement('SCRIPT');cbt_script.type='text/javascript';cbt_script.src='https://crossbrowsertesting.com/cbt_bookmarklet.js.php?random='+(new Date()).getTime();document.getElementsByTagName('head')[0].appendChild(cbt_script);}else{showCBTbookmarklet();}})();

所以现在的问题只有 "how do i make javascript edit the current adress?" 好吧,这很简单,只需使用 window.location.href = '';

例如:

javascript:(function(){window.location.href='https://google.com'})();

会带你去https://google.com

所以现在我们让 javascript 获取当前页面并对其进行一些转换:

// The weird structure of the function is because it's a "self running"
// function, they look like this (function(){/*code*/})();
(function () {
var currentUrl = window.location.href;
var newUrl = currentUrl.replace("https://", "https://ps.");
window.location.href = newUrl;
}();

或以书签形式缩短:

javascript:(function(){location.replace(window.location.href.replace("https://","https://ps."))})();

这会变成例如按书签时https://google.com进入https://ps.google.com

注意开头要有http或https,否则location.replace函数不会按你想要的方式打开。