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

问题描述 投票:-1回答:1

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

javascript bookmarklet userscripts
1个回答
0
投票

你在谈论什么是“书签”。

在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函数将无法以您希望的方式打开它。

© www.soinside.com 2019 - 2024. All rights reserved.