How does it work?
In order to build a bookmarklet with this framework, all you need is to create an options file. In this file, the object window.bookmarklet.options have to be created, including some optional properties:
- css (string/array)
- An string with the url of an external css file to load. If you want load more than one file, you can use an array.
- js (string/array)
- An string with the url of an external javascript file to load. You can use an array to load various files.
- jquery (string)
- Define the url to load the jQuery library if you need it.
- ready (function)
- A function with the code for the bookmarklet. It will be executed when all previous files (css, js and jquery) have been loaded.
Once your options file was created, it would be possible to launch your bookmarklet with the following code:
(function (b, f) {
if (window.bookmarklet == undefined || window.bookmarklet.launch == undefined) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = b;
document.body.appendChild(s);
s.onload = function () {
window.bookmarklet.launch(f);
};
s.onreadystatechange = function () {
if (s.readyState == 'loaded' || s.readyState == 'complete') {
s.onload();
}
}
} else {
window.bookmarklet.launch(f);
}
})('bookmarket.js', 'options.js');
Or also creating a hyperlink with the code minified:
<a href="javascript:(function(b,f){if(window.bookmarklet==undefined||window.bookmarklet.launch==undefined){var s=document.createElement('script');s.type='text/javascript';s.src=b;document.body.appendChild(s);s.onload=function(){window.bookmarklet.launch(f);};s.onreadystatechange=function(){if(s.readyState=='loaded'||s.readyState=='complete'){s.onload();}}}else{window.bookmarklet.launch(f);}})('bookmarket.js','options.js');">Name of your bookmarklet</a>
Simple example
Let's say we want make a simple bookmarklet to share the current page in twitter. Ok, to do that, we don't need any framework but this is just an example. We need to create a javascript file with the following code:
window.bookmarklet.options = {
ready: function() {
var url = 'http://www.twitter.com/home?status=' + window.location.href;
window.location.href = url;
}
};
Loading external javascript or css files
This is an example of bookmarklet loading various external javascript files to make something more complex:
window.bookmarklet.options = {
js: ['http://mysite.com/bookmarklet/script1.js', 'http://mysite.com/bookmarklet/script2.js'],
ready: function() {
//The bookmarklet code
}
};
Loading jQuery
Example of bookmarklet using jQuery. This one loads a css file from google webfonts and apply it to all headers of the page. The function ready() has one parameter, with the alias of the jQuery element (for example "$"):
window.bookmarklet.options = {
css: 'http://fonts.googleapis.com/css?family=Ubuntu:regular,bold',
jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',
ready: function($) {
$(':header').css('font-family', 'Ubuntu');
}
};