Greasemonkey And Dojo Integration Redux

Back in 2007 I wrote a post on how to integrate Dojo with Greasemonkey.

Since then, Greasemonkey has been re-written to include security and bug fixes which has broken my demo code. The problem is that the new security model doesn’t return an instance to the newly created dijit.Dialog when the constructor is called. The work-around is to set the ID of the dialog, and then call dijit.byId() to get a handle to it.

Of course, this is going to pose problems when creating non-dijit objects, as they will all be created on the page-level scope. The work-around is likely constructing clever eval() strings, and then accessing the objects using unsafeWindow. If anyone comes up with a more elegant solution, let me know about it in the comments.

The following can be used to overwrite the previous version of the user-script, restoring the broken functionality as well as making use of some of the newly introduced Dojo features.

// ==UserScript==
// @name           Dojo Integration Test
// @namespace      test
// @description    Proof Of Concept To Integrate Dojo And Greasemonkey
// @include        *
// ==/UserScript==

function startup(){
    dojo = unsafeWindow["dojo"];
    dijit = unsafeWindow["dijit"];

    dojo.addClass(dojo.body(), 'tundra');
    dojo.require("dijit.Dialog");

    //Don't do anything until "Dijit.Dialog" has been loaded
    dojo.addOnLoad(function(){
        //Actually Create The Dialog
        new dijit.Dialog({
            id: 'test',
            title: "Dojo Integration Test",
            content: 'Dojo lives... In Greasemonkey'
        });

        dijit.byId('test').show();
    });
};

//include flags to djConfig to tell dojo its being used after its been loaded
unsafeWindow.djConfig = {
    afterOnLoad: true,
    addOnLoad: startup
};

//Include Dojo from the AOL CDN
var script = document.createElement('script');
script.src="http://o.aolcdn.com/dojo/1.4/dojo/dojo.xd.js.uncompressed.js";
document.getElementsByTagName('head')[].appendChild(script);

//Include the Tundra Theme CSS file
var link = document.createElement('link');
link.rel = "stylesheet";
link.type= "text/css";
link.href="http://o.aolcdn.com/dojo/1.4/dijit/themes/tundra/tundra.css";
document.getElementsByTagName('head')[].appendChild(link);