PHP class to convert JS into valid bookmarklet links

1.2 2017-05-18 12:46 UTC

This package is auto-updated.

Last update: 2021-04-09 12:16:26 UTC


Convert readable Javascript code into bookmarklet links


  • removes comments

  • compresses code by removing extraneous spaces, but not within literal strings. Example:

    function   someName(   param   ) {
     alert( "this is a string" )

    will return:

  • encodes what needs to be encoded

  • wraps code into a self invoking function ready for bookmarking

This is basically a slightly enhanced PHP port of the excellent Bookmarklet Crunchinator: http://ted.mielczarek.org/code/mozilla/bookmarklet.html


If you are using Composer, add this requirement to your composer.json file and run composer install:

    "require": {
        "ozh/bookmarkletgen": "1.2.0"

Or simply in the command line : composer install ozh/bookmarkletgen

If you're not using composer, download the class file and include it manually.


$javascript = <<<CODE
var link="http://google.com/"; // destination
window.location = link;

require 'vendor/autoload.php'; // if you install using Composer
require 'path/to/Bookmarkletgen.php'; // otherwise

$book = new \Ozh\Bookmarkletgen\Bookmarkletgen;
$link = $book->crunch( $javascript );

printf( '<a href="%s">bookmarklet</a>', $link );

will print:

<a href="javascript:(function()%7Bvar%20link%3D%22http%3A%2F%2Fgoogle.com%2F%22%3Bwindow.location%3Dlink%3B%7D)()%3B">bookmarklet</a>


This library comes with unit tests to make sure the resulting crunched Javascript is valid code.

This library requires PHP 5.3. Tests are failing on HHVM because of an external binary issue (phantomjs) but things should work anyway on HHVM too.


Do whatever the hell you want to do with it