Search code examples
javascripthtmlescapingjekyllliquid

How to create bookmarklet from file in Jekyll?


I've got an old project with a bookmarklet which has some slightly technical instructions to convert a JavaScript file into a bookmarklet by basically creating a dummy bookmark and replacing the location field. I'd like to change this into a bookmarklet on my Jekyll-generated blog, so that users can simply drag and drop the link to the bookmark bar to install it.

One hard requirement is keeping the JavaScript code in a separate file (to be easily modified and linted), and, if at all possible, to not have to keep two versions of the file in sync. What I've tried so far is this:

[foo][1]

[1]:javascript:{% include foo.js %}

But this doesn't escape the JavaScript code, so the web page ends up being a mess of a link and a <code> block. I also tried include foo.js | escape, which seems to be a syntax error.

How can I include a file and escape it to be usable as a bookmarklet?


Solution

  • This does the right thing, URL-encoding the contents of the JavaScript file with %20 for spaces*:

    [foo][1]
    {% capture raw_bookmarklet %}{% include foo.js %}{% endcapture %}
    [1]:javascript:{{ raw_bookmarklet | uri_escape }}
    

    Resulting code and page.

    *: url_encode replaces spaces with +, resulting in syntax errors.