45
submitted 1 year ago* (last edited 1 year ago) by Crul@lemm.ee to c/firefox@lemmy.ml

In Firefox you can combine JS bookmarklets, keywords and params to do something like this:

javascript:(function(){
    var args = '%s'.split(' ');
    alert(args);
})();

Useful example:

javascript:(function(){
    var args = '%s'.split(' ');
    var subreddit = args[0];
    var search = args[1];
    document.location.href = "https://www.reddit.com/r/" + subreddit + "/search/?q=" + search + "&include_over_18=on&restrict_sr=on&t=all&sort=new";
})();

Bookmarklet format:

javascript:(function() {var args = '%s'.split(' ');var subreddit = args[0];var search = args[1];document.location.href = "https://www.reddit.com/r/" + subreddit + "/search/?q=" + search + "&include_over_18=on&restrict_sr=on&t=all&sort=new";})();

If you assign the keyword redditsearch to that bookmarklet, you can type redditsearch PixelArt zelda on the firefox navbar and you will be reditected to the Reddit search for 'zelda' on r/PixelArt.

In general this makes the navbar a very powerful command line in which you can add any command with multiple params.


It seems Mozilla has plans to get rid of this feature, see the ticket Migrate keyword bookmarks into about:preferences managed Search Engines. The good news is that the last comment, besides mine asking them not to remove this functionality, is from some years ago. I hope they change their mind, or forget about it...


TIP: If you don't want to remember the param order, you can also ask for them with a prompt if no arguments are specified:

javascript:(function(){
    var args = '%s'.split(' ');
    var subreddit = args[0] != "" ? args[0] : prompt("Enter the subbreddit:");
    if (!subreddit) return;
    var search = args.length > 1 ? args[1] : prompt("Enter the text to search:");
    if (!search) return;
    document.location.href = "https://www.reddit.com/r/" + subreddit + "/search/?q=" + search + "&include_over_18=on&restrict_sr=on&t=all&sort=new";
})();

Bookmarklet format:

javascript:(function(){ var args = '%s'.split(' '); var subreddit = args[0] != "" ? args[0] : prompt("Enter the subbreddit:"); if (!subreddit) return; var search = args.length > 1 ? args[1] : prompt("Enter the text to search:"); if (!search) return; document.location.href = "https://www.reddit.com/r/" + subreddit + "/search/?q=" + search + "&include_over_18=on&restrict_sr=on&t=all&sort=new"; })();

Sorry for the reddit examples, this was posted originally on r/firefox some time ago and adapting them to lemmy seemed a bit too much work :P.

you are viewing a single comment's thread
view the rest of the comments
[-] Crul@lemm.ee 2 points 1 year ago* (last edited 1 year ago)

(... continues from previous comment, I was getting an error when I tried to post all in the same comment)

post image to reddit

I don't recommend this one, I haven't used in a while and it doesn't work great with most sites.

It should works very similar to the previous one, but looking for images on the page. It also writes my usual "Source: [title](url) blablabla" comment for the most common sites.

The result is a huge mess and very fragile. I post it more as an example of how you could do some things.

pretty printed code

javascript: (function(clipboard) {
    var subKeys = {
        cf: 'CassetteFuturism',
        cm: 'cybermonk',
        dp: 'decopunk',
        it: 'ImaginaryTechnology',
        iso: 'isometric',
        iv: 'ImaginaryVehicles',
        ap: 'ApocalypsePorn',
        ss: 'Simon_Stalenhag',
        sw: 'spainwave',
        sk: 'sketches',
    };
    var args = '%s'.split(' ');
    var subreddit = args[0];
    if (!subreddit) {
        var promptText = "Type subreddit:";
        for (var shortcut in subKeys) promptText += `\n- ${shortcut}: ${subKeys[shortcut]}`;
        subreddit = prompt(promptText);
    }
    if (!subreddit) return;
    if (subKeys[subreddit]) subreddit = subKeys[subreddit];
    var data = getData();
    if (!data) return;
    data.url = encodeURIComponent(data.url);
    window.open(`https://www.reddit.com/r/${subreddit}/submit?url=${data.url}&title=${data.title}`);
    if (!data.comment) return;
    if (clipboard) clipboard.writeText(data.comment);
    showComment(data.comment);

    function getData() {
        var imgs;
        var title = document.title;
        var comment = "";
        var isArtStation = document.location.host.endsWith("artstation.com");
        var isFlickr = document.location.host.endsWith("flickr.com");
        var isDeviantArt = document.location.host.endsWith("deviantart.com");
        if (isArtStation) {
            imgs = [...document.querySelectorAll(".project-assets-list picture img")];
            if (!imgs.length) {
                imgs = [...document.querySelectorAll(".project-assets img")];
            }
        } else if (isFlickr) {
            imgs = document.getElementsByClassName("zoom-large");
            if (!imgs.length) {
                alert("No large zoom image found.");
            }
        } else if (isDeviantArt) {
            var deviantArtImgRegex = /\/w_\d+,h_\d+/;
            imgs = [...document.querySelectorAll(".ReactModalPortal img")].filter(img => !(deviantArtImgRegex.exec(img.src)));
            if (!imgs.length) {
                alert("No large zoom image found.");
            }
        } else {
            imgs = document.getElementsByTagName("img");
        }
        if (!imgs.length) return;
        var imgIdx = undefined;
        if (imgs.length > 1) {
            if (args.length > 1) imgIdx = parseInt(args[1]);
            if (imgIdx === undefined || isNaN(imgIdx) || imgIdx < 1 || imgIdx > imgs.length) {
                numberImgs();
                imgIdx = parseInt(prompt(`There are ${imgs.length} images, select index:`, 1));
            }
            if (isNaN(imgIdx) || imgIdx < 1 || imgIdx > imgs.length) return;
            url = imgs[imgIdx - 1].src;
        } else {
            url = imgs[0].src;
        }
        if (isArtStation) {
            var data = getArtStationData(imgs);
            title = data.title;
            comment = data.comment;
        } else if (isFlickr) {
            var data = getFlickrData();
            title = data.title;
            comment = data.comment;
        } else if (isDeviantArt) {
            var data = getDevianArtData();
            title = data.title;
            comment = data.comment;
        }
        return {
            title: title,
            url: url,
            comment: comment
        };
    }

    function getArtStationData(imgs) {
        var title = document.querySelector(".project-sidebar-inner h1");
        if (!title) title = document.querySelector(".artwork-info-container h1");
        if (!title) return;
        var author = document.querySelector(".project-author-name a");
        if (!author) author = document.querySelector(".artist-name-and-headline .name a");
        if (!author) return;
        var withMoreImages = imgs.length > 1 ? " **with more images**" : "";
        var comment = `Source${withMoreImages}: [${title.innerText} (by ${author.innerText} - ArtStation)](${document.location.href})`;
        var desc = document.querySelector(".project-description p:first-child");
        if (!desc) desc = document.querySelector("#project-description p:first-child");
        if (desc) comment += formatRedditCommentQuote(desc.innerText);
        return {
            title: `${title.innerText} (by ${author.innerText})`,
            comment: comment
        };
    }

    function getFlickrData() {
        var author = document.getElementsByClassName("owner-name")[0].innerText;
        var title = document.title.substr(0, document.title.length - 9);
        if (title.indexOf(author) < 0) {
            title += ` (${author})`;
        }
        var comment = `Source: [${title} (Flickr)](${document.location.href})`;
        var desc = document.querySelector(".title-desc-block h1");
        if (!desc) desc = document.querySelector(".title-desc-block h2");
        if (desc) comment += formatRedditCommentQuote(desc.innerText);
        return {
            title: title,
            comment: comment
        };
    }

    function getDevianArtData() {
        var userLinkElems = document.querySelectorAll("a.user-link");
        if (userLinkElems.length < 2) return;
        var title = document.querySelector('h1[data-hook="deviation_title"]');
        if (!title) return;
        var comment = `Source: [${title.innerText} (by ${userLinkElems[1].innerText} - DeviantArt)](${document.location.href})`;
        var desc = document.querySelector(".legacy-journal");
        if (desc) comment += formatRedditCommentQuote(desc.innerText);
        return {
            title: `${title.innerText} (${userLinkElems[1].innerText})`,
            comment: comment
        };
    }

    function showComment(comment) {
        var inpt = document.getElementById("source-code");
        if (!inpt) {
            inpt = document.createElement("textarea");
            inpt.id = "source-code";
            inpt.style.position = "fixed";
            inpt.style.color = "black";
            inpt.style.top = "72px";
            inpt.style.width = "720px";
            inpt.style.height = "120px";
            inpt.style.zIndex = "99999";
            inpt.style.lineHeight = "normal";
            inpt.ondblclick = () => inpt.select();
            document.body.appendChild(inpt);
        };
        inpt.value = comment;
        inpt.focus();
        inpt.select();
    }

    function formatRedditCommentQuote(quote) {
        while (quote.indexOf("\n\n") >= 0) quote = quote.replaceAll("\n\n", "\n");
        return `: \r\n> ${quote.replaceAll("\n", "  \n")}`;
    }

    function numberImgs() {
        var imgs;
        var isArtStation = document.location.host.endsWith("artstation.com");
        if (isArtStation) {
            imgs = [...document.querySelectorAll(".project-assets-list picture img")].concat([...document.querySelectorAll(".project-assets img")]);
        } else {
            imgs = document.getElementsByTagName("img");
        }
        for (var img = 0; img < imgs.length; img++) {
            var parent = imgs[img].parentElement;
            if (!parent) continue;
            var numberDiv = document.createElement("div");
            numberDiv.innerHTML = 1 + img;
            numberDiv.style.position = "absolute";
            numberDiv.style.padding = "2px 9px 2px 6px";
            numberDiv.style.background = "rgba(255, 0, 0, 0.5)";
            numberDiv.style.zIndex = "9999";
            parent.prepend(numberDiv);
        }
    }
})(navigator.clipboard)

(one-liner missing because I'm still getting an error)

EDIT: Yeah, lemmy doesn't like a single line with >5000 characters, hehe. Anyway, I don't recommend using this last one.

[-] Zeus@lemm.ee 1 points 1 year ago

holy hell that is an absolute monolith of a bookmarklet though

[-] Crul@lemm.ee 2 points 1 year ago

Yep... sadly (AFAIK) reusing code in bookmarklets is not a thing to make it more mantainable.

this post was submitted on 24 Aug 2023
45 points (100.0% liked)

Firefox

17303 readers
25 users here now

A place to discuss the news and latest developments on the open-source browser Firefox

founded 4 years ago
MODERATORS