This is the documentation for the binding of Python and the Mozilla DOM. This allows you to use Python code (almost) anywhere you can use JavaScript.

Globals and namespaces

This is taken from a mail to the pyxpcom list - it should be expanded, but a copy-paste will do for now

Normal module semantics don't exist here. The globals are 'bound' to the global object (i.e., the window), instead of to a module's __dict__ as you expect in the Python world. Note that we don't actually 'import' anything here - the scripts and event handlers do not exist in a Python module.

The intent is to provide similar semantics to JS. For example, when a top-level window has something like:

<window ...
 script="foo = 1"

An event handler like:

  <button onclick="print foo"/>

Should be able to reference 'foo' via globals as shown.

Note that you can stick arbitrary values on any DOM object - this is what JS calls 'expandos'. For example, let's say you have XUL similar to pyxultest:

Top-level script code says something like:

button = document.getElementById("some-button") = 0

And the button itself might look like:

<button id="some-button" label="click here"
        onclick=" += 1; print 'Foo is now',"/>

Note that (a) we have stuck an arbitrary attribute on a DOM element and (b) in all cases (e.g., event handler and top-level script), the DOM node needs to be explicitly specified - the globals are the window itself. The event handler could also have used getElementById - the point is that both the event handler and top-level script share the same namespace.

Using Python

Ideally, you just tell Mozilla you are using Python, and magically you can use Python instead of JavaScript. Once you set the script type for a node, it is the default for that node and all children. This means that if you set the script-type to Python for the window, Python is the default script type for all child elements in the window.


Use a script-type attribute on your elements. For example,

 <window script-type="application/x-python" .../>


<meta http-equiv="Content-Script-Type" content="application/x-python" /> should work (but possibly doesn't - see bug 100924). But addEventListener within a <script type="application/x-python"> block does.


Python code can not be secured - so it will only run from trusted sources. This means you can only have Python code in chrome. Content loaded from anywhere other than a chrome:// URL can not host Python. It should be obvious why you don't want to run in your browser! Inside chrome, you can use Python via either HTML or XUL.

PyXPCOM: Create and use XPCOM components with Python
PyDOM Samples: Sample applications that use PyDOM
PythonExt: A Firefox/XULRunner extension that can be used to install PyDOM