Thursday, March 13, 2014

PrototypeJS Bookmarklet

I like playing around on sites, and sometimes I need to extract data a page using javascript, since I am very familiar with PrototypeJS, I need to be able to include it easily on any page, so I wrote a small bookmarklet to do just that, it is based of some of the jQuery bookmarklets, anyway here it is:

/* @author Willie Scholtz */
(function() {
    var prototypeUrl = 'https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js',
        css = '#prototype-message{padding:3px;background-color:#000;color:#fff;text-align:center;position:fixed;left:0;top:0;width:100%;height:auto;z-index:9999;text-shadow:1px 1px 3px #fff;}',
        head = document.head || document.getElementsByTagName('head')[0],
        body = document.body || document.getElementsByTagName('body')[0], 
        style, messDiv;
 
    if ((style = document.getElementById('prototype-style')) === null) {
        style = document.createElement('style');
        style.type = 'text/css';
        style.id = 'prototype-style';
 
        head.insertBefore(style, head.firstChild);
        style.appendChild(document.createTextNode(css));
    }
 
    if ((messDiv = document.getElementById('prototype-message')) === null) {
        messDiv = document.createElement('div');
        messDiv.id = 'prototype-message';
        messDiv.style.display = 'none';
 
        body.insertBefore(messDiv, body.firstChild);
    }
 
    function insertScript(url, succ) {
        var scr = document.createElement('script'), done = false;
        scr.src = url;
 
        scr.onload = scr.onreadystatechange = function() {
            if (!done && !this.readyState || this.readyState.match(/loaded|complete/)) {
                done = true;
                succ.call(this);
                scr.onload = scr.onreadystatechange = null;
            }
        }
 
        head.appendChild(scr);
    }
 
    function message(msg) {
        messDiv.innerText = msg;
        messDiv.style.display = 'block';
 
        setTimeout(function() {
            messDiv.style.display = 'none';
        }, 2000);
    }
 
    if (typeof window.Prototype !== 'undefined') {
        message('This page already has PrototypeJS, yay!');
    } else {
        insertScript(prototypeUrl, function() {
            message('PrototypeJS has been added to this page, yay!');
        });
    }
})();

Save it as a bookmark and remember to add javascript: in front of the code.