Search code examples
javascriptbookmarkletuserscripts

Can this bookmarklet be converted to Greasemonkey userscript?


I'm not quite sure how to convert this code from a bookmarklet to a userscript because it uses URL-encoded characters:

javascript:var%20multiURL="";%20$('div.titlebox').find('ul.subreddits').find('a').each(function()%20{%20multiURL%20+=%20$(this).text().substr(3)%20+%20"+";%20});%20multiURL%20=%20multiURL.substr(0,multiURL.length-1);%20window.open('http://www.reddit.com/r/'+multiURL);void(0);

Ideas?


Solution

  • First, you have to convert the URL-encoded characters into regular ones, which Jared Farrish has kindly done with a bit of PHP wizardry. If you need to do this in the future, you can try this online URL encoder/decoder.

    That gives you this JavaScript blob:

    javascript:var multiURL=""; $('div.titlebox').find('ul.subreddits').find('a').each(function() { multiURL += $(this).text().substr(3) + "+"; }); multiURL = multiURL.substr(0,multiURL.length-1); window.open('http://www.reddit.com/r/'+multiURL);void(0);
    

    Formatted and converted to proper JS:

    var multiURL = "";
    $('div.titlebox').find('ul.subreddits').find('a').each(function () {
        multiURL += $(this).text().substr(3) + "+";
    });
    multiURL = multiURL.substr(0, multiURL.length - 1);
    window.open('http://www.reddit.com/r/' + multiURL);
    

    Then, all that's left to do is use userscript notation and save it in a file with a name that ends in .user.js (important).

    // ==UserScript==
    // @name           Author's Name
    // @namespace      Place where file is stored
    // @include        Place(s) where userscript should run
    // ==/UserScript==
    
    var multiURL = "";
    $('div.titlebox').find('ul.subreddits').find('a').each(function () {
        multiURL += $(this).text().substr(3) + "+";
    });
    multiURL = multiURL.substr(0, multiURL.length - 1);
    window.open('http://www.reddit.com/r/' + multiURL);
    

    It's important to note that this will run at every address listed with @include, so you might want to consider injecting a button or something onto relevant pages so that it doesn't run unnecessarily.