Sunday, August 12, 2018

Generate bookmarklet dynamically from gist

Let's say you want to make some bookmarklets be available to readers of your website and you want to be able to update them conveniently without having to re-encode your javascript into a bookmarklet and edit your website html. Here's a simple method. Post the bookmarklet on gist.github.com, and then edit and use the following html/javascript code to fetch the javascript and automatically generate a bookmarklet:

<p>My bookmarklet is here: <a href="__error__" id="myBookmarklet1">My Bookmarklet</a>.</p>
<script>
var linkId = "myBookmarklet1";
var gistLink = "https://gist.githubusercontent.com/arpruss/74abc1bc95ae08e543b9b74f15a23b07/raw";
fetch(gistLink).then(function(response) {
    if (!response.ok) {
        //alert("Error fetching "+response.statusText);
    }
    else {
        response.text().then(function(text) {
            var link = document.getElementById(linkId);
            link.href = "javascript:"+encodeURIComponent("(function(){"+text+"})()");
        });
    }
}); 
</script>

For a live example, see my previous post.

No comments:

Post a Comment