manalang

manalang

  • 02:47:02 pm on January 4, 2006 | # |
    Tags: ,

    I’m working on a new Greasemonkey script and with the recent discovery of cross-domain access to JSON data, I figured the same technique would be a good way to bring in JavaScript libraries that can be useful in your Greasemonkey scripts. The only hitch is that you have to trust the host of the libraries you want to bring in… else it’s possible to cause harm to your users.

    Here’s an example of how I can load the Prototype library. The key thing here is that you have to wait for the external JavaScript file to load before you can use it. I do this by recursively checking if a variable is available (see the waitForProto function).  Once the library is loaded, I continue with the rest of my script.

    var p = unsafeWindow;
    function waitForProto() {
        if (typeof p.Prototype=='undefined')
    	// set to check every 100 milliseconds if the libary has loaded
            window.setTimeout(waitForProto, 100);
        else
            // call the rest of your code
    }
    function loadProto() {
    	// dynamically creates a script tag
            var proto = document.createElement('script');
            proto.type = 'text/javascript';
            proto.src = 'http://prototype.conio.net/dist/prototype-1.3.1.js';
            document.getElementsByTagName('head')[0].appendChild(proto);
            waitForProto();
    }
    window.addEventListener('load', loadProto(), false);
    

    By the way, after the library is loaded, you can access the “p” object to gain access to the Prototype objects. “p” is a reference to Greasemonkey’s unsafeWindow object.

    Has anyone figured out a better way to do this?

    Technorati Tags: ,

     

Trackbacks

close Reblog this comment
blog comments powered by Disqus