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

时间:2017-12-16 00:44:50

标签: javascript bookmarklet userscripts

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

1 个答案:

答案 0 :(得分:0)

你正在谈论的是什么" bookmarklet"。

在Chrome中,打开书签栏。右键单击它,按"添加页面",给它起一个名字,然后粘贴一个javascript函数的值(而不是URL),例如像这样(摘自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();}})();

所以现在问题只是"我如何让javascript编辑当前的地址?"那很简单,只需使用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函数无法按照您希望的方式打开它。

相关问题