Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created October 18, 2017 21:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loretoparisi/7b27583fd1dc0cb32a8ac5e96e2e0449 to your computer and use it in GitHub Desktop.
Save loretoparisi/7b27583fd1dc0cb32a8ac5e96e2e0449 to your computer and use it in GitHub Desktop.
Create a bookmarklet from JavaSscript code
function minify(code) {
// very simple minification (and not overly aggressive on whitespace)
code = code.split(/\r\n|\r|\n/g);
var i=0, len=code.length, noSemiColon = {}, t, lastChar;
$.each('} { ; ,'.split(' '), function(i, x) {
noSemiColon[x] = 1;
});
for (; i<len; i++) {
// note: this doesn't support multi-line strings with slashes
t = $.trim(code[i]);
// this breaks when I put turnaries on multiple lines -- I'll leave it up
// to the bookmarklet writers to do semi-colons properly
// if (t) {
// // add semi-colon if we should
// if (!noSemiColon[t.charAt(t.length-1)]) {
// t += ';';
// }
// // prevent the inadvertently calling a function scenario
// if (i!=0 && t && t.substr(0, 1)=='(' && code[i-1].charAt(code[i-1].length-1)!=';') {
// t = ';' + t;
// }
// }
code[i] = t;
}
return code.join('').replace(/;$/, '');
}
function scriptLoader(code, path, isJQuery) {
return (''
+ 'function callback(){'
+ (isJQuery ? '(function($){var jQuery=$;' : '')
+ code
+ (isJQuery ? '})(jQuery.noConflict(true))' : '')
+ '}'
+ 'var s=document.createElement("script");'
+ 's.src="' + path + '";'
+ 'if(s.addEventListener){'
+ 's.addEventListener("load",callback,false)'
+ '}else if(s.readyState){'
+ 's.onreadystatechange=callback'
+ '}'
+ 'document.body.appendChild(s);'
);
}
function asBookmarklet(code, jQueryPath, customPath) {
code = minify(code);
if (customPath) {
code = scriptLoader(code, customPath, false);
}
if (jQueryPath) {
code = scriptLoader(code, jQueryPath, true);
}
code = '(function(){' + code + '})()';
return 'javascript:' + encodeURIComponent(code);
}
@loretoparisi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment