Monday, February 09, 2009

Playing around XUL, JavaScript and jQuery

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<x:window
    xmlns:x="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    xmlns="http://www.w3.org/1999/xhtml"
>
    <x:script type="application/x-javascript"
        src="file:///c:/xul/jquery-1.2.6.js"
    />
 
<x:script type="application/x-javascript; e4x=1">
<![CDATA[
  function test(){
    $('#b').attr("label", "3");
    var frag =
        <listitem value="4"
            label="new item"
            xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        />;
    $('#l').get(0)
        .appendChild(
            (new DOMParser()).parseFromString(
                frag.toXMLString(), 'text/xml'
            ).documentElement
        );
  }
]]></x:script>
     
    <x:button label="click me" oncommand="test();"/>
    <x:button id="b" label="2"/>
    <x:listbox id="l">
        <x:listitem value="1" label="item label"/>
        <x:listitem value="2" label="item label"/>
        <x:listitem value="3" label="item label"/>
    </x:listbox>
 
</x:window>



The above code is to dynamically adding a new <listitem/> into listbox #l. It will be working fine when we get some XUL fragment remotely from the server-side as well. This is Gecko 1.9.0.5.

What I've learned:
  • $("#id").get(0) returns a single element, while .get() returns a list.
  • e4x=1 tells the JavaScript parser to use the newer language spec.
  • jQuery works fine with XUL, but XML namespace is needed to avoid some gotcha because it's been designed to work with HTML, not actually XUL.
  • DOMParser works as expected
  • Gecko 1.9 solved a lot of bugs I was encountering in 1.8.
  • With Grails as a back-end, we can now create a dynamically half-Web/half-desktop app.

3 comments:

Ho denunciato Dio per stalking said...

Hi, i did some similiar with my FF extension but it broke some other installed estensions like diigo toolbar.

Puja said...

Can you help in answering questions of java script

http://mindgrillq.blogspot.com/search/label/JavaScript

Leon Victor said...

I want to create a popup to display the results of the application process is done, I want to use jQuery. I want to ask whether it is possible to use jQuery in XUL?