Search code examples
javascriptbookmarkletuserscripts

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


I want to know how I can create a script that replaces "https://www." in the Reddit URL, with "ps." when I click a bookmark. Does anyone know how I can do this? My programming knowledge is pretty limited.


Solution

  • What you're talking about it a "bookmarklet".

    In Chrome, open up the bookmark bar. Right click it, press "Add page", give it a name, then paste in as a value (instead of a URL) a javascript function, e.g. like this (taken from 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();}})();
    

    So now the question is only "how do i make javascript edit the current adress?" Well that's easy, just use window.location.href = '';

    so for example:

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

    Will take you to https://google.com.

    So now we make the javascript take the current page and transform it somewhat:

    // 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;
    }();
    

    Or in bookmarklet form and shortened down:

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

    This would turn e.g. https://google.com into https://ps.google.com when you press the bookmark.

    Note that you need http or https at the start, otherwise the location.replace function won't open it the way you want it to.