Samples Of Code

Restart Firefox

const appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1'].getService(Components.interfaces.nsIAppStartup);
appStartup.quit(appStartup.eRestart+appStartup.eForceQuit);

Obtain a preference

var gPrefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var pref = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
about_config.jpg

Manage all opened windows of type "navigator:browser"

var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
var windows = windowManagerInterface.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) 
{
  var fenetre = windows.getNext();
  var urlBar = fenetre.document.getElementById("urlbar");
  if (urlBar) alert(urlBar.localName);
}

Work with a MutableArray

var marr = Components.classes["@mozilla.org/array;1"].createInstance(Components.interfaces.nsIMutableArray);
var element = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
element.data = "firstElement";
marr.appendElement(element, false);
var result =  marr.queryElementAt (0 ,Components.interfaces.nsISupportsString);
alert(result.data); //firstElement

Access to metadata bundle

toto.properties

imageToExplore=http://www.google.fr/intl/fr_fr/images/logo.gif

toto.xul

...
<script type="application/x-javascript" src="chrome://name_of_package/content/toto.js"/>
<stringbundle src="chrome://name_of_package/content/toto.properties" id="bundle_metadata"/>
...

toto.js

var gMetadataBundle = document.getElementById("bundle_metadata");
var imageToExplore = gMetadataBundle.getString("imageToExplore");

Access to image in cache

+++ global declaration

var httpCacheSession;

+++ onLoad

const cacheService = Components.classes["@mozilla.org/network/cache-service;1"].getService(Components.interfaces.nsICacheService);
httpCacheSession =  cacheService.createSession("HTTP", 0, true);
httpCacheSession.doomEntriesIfExpired = false;

+++ after

var imageToExplore = "http://www.google.fr/intl/fr_fr/images/logo.gif";
var cacheEntryDescriptor = httpCacheSession.openCacheEntry(imageToExplore, Components.interfaces.nsICache.ACCESS_READ, false);
if(cacheEntryDescriptor)
{
    alert("size : "+cacheEntryDescriptor.dataSize);
    alert("isStreamBased() : " + cacheEntryDescriptor.isStreamBased());
}

Load url in iframe

toto.xul

...
<script type="application/x-javascript" src="chrome://name_of_package/content/toto.js"/>
...
<iframe id="ifr1" type="content" flex="1" src="" />

toto.js

var urlToOpen = "http://yahoo.fr";
var ifr1 = document.getElementById("ifr1"); 
ifr1.webNavigation.loadURI(urlToOpen, Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);

or with baseURI

var urlToOpen = "http://yahoo.fr";
var ifr1 = document.getElementById("ifr1"); 
var baseURI = ioService.newURI("http://www.google.fr", "UTF-8", null);
ifr1.webNavigation.loadURI(urlToOpen, Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE, baseURI, null, null);

or local file

ifr1.webNavigation.loadURI("file:///home/tanio/language/anglais/words/willing.wav", Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);

Download a file

var fileToDownload="http://www.spanishdict.com/a/en/legend-e.wav";
var localFileName="/home/tanio/Desktop/legend.wav";
saveURL(fileToDownload,localFileName);

function saveURL(strSource, strDestination)
{
    var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance();
    aFile.QueryInterface(Components.interfaces.nsILocalFile);
    aFile.initWithPath(strDestination);

    try
    {
        var source = makeURL(strSource);
        var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
        const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
        persist.persistFlags = nsIWBP.PERSIST_FLAGS_NO_CONVERSION | nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES | nsIWBP.PERSIST_FLAGS_FROM_CACHE;
        persist.saveURI(source, null, null, null, null, makeFileURL(aFile));
        return true;
    }
    catch(e)
    {alert(e); return false;}
}

function makeURL(aURL)
{
  var ioService = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
  return ioService.newURI(aURL, null, null);
}

function makeFileURL(aFile)
{
  var ioService = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
  return ioService.newFileURI(aFile);
}

Use a nsICollection

the nsICollection can contain only objects that implements nsISupports interface

function objtest(membre)
{
    this.m = membre;
}

objtest.prototype = {

    QueryInterface : function(aIID)
    {
      const Ci = Components.interfaces;
      if (aIID.equals(Ci.nsISupports))
        return this;
      throw Components.results.NS_NOINTERFACE;
    }
}

var dictionnaire = Components.classes["@mozilla.org/supports-array;1"].createInstance(Components.interfaces.nsICollection);
var wt = new objtest("toto");
dictionnaire.AppendElement (wt);
alert(dictionnaire.Count()+"");

Read a text file in UTF format into a text variable data

try
{
    var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    var source = ioService.newURI("chrome://english_testing/content/anglais_francais.txt", "utf-8", null);
    var channel = ioService.newChannelFromURI(source);
    var inputStream =  channel.open();
    var sis = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
    sis.init(inputStream);
    var data = "";
    var str = sis.read(-1);
    while (str.length > 0)
    {
        data += str;
        str = sis.read(-1);        
    }
    sis.close();
    inputStream.close();

    var utf8Converter = Components.classes["@mozilla.org/intl/utf8converterservice;1"].getService(Components.interfaces.nsIUTF8ConverterService);
    data = utf8Converter.convertURISpecToUTF8 (data, "UTF-8");
}
catch(e)
{}

Choice a file or folder by browsing

var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
picker.appendFilters(Components.interfaces.nsIFilePicker.filterAll);
//folder
picker.init (window, "Choice folder", Components.interfaces.nsIFilePicker.modeGetFolder);
//or file
picker.init (window, "Choice file", Components.interfaces.nsIFilePicker.modeOpen);
if (picker.show() == Components.interfaces.nsIFilePicker.returnOK)
    alert(picker.file.path);

Testing if file exists

function fileExists(localFileName)
{
    try
    {
        var fSource = Components.classes["@mozilla.org/file/local;1"].createInstance();
        fSource.QueryInterface(Components.interfaces.nsILocalFile);
        fSource.initWithPath(localFileName);
        return fSource.exists();
    }
    catch(e)
    {
        alert(e);
        return false;
    }
}

Write to the console

var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
consoleService.logStringMessage("I log my message");

OBJECTS

create an empty object and use them

var point = {};
point.x = 5;
point.y = 10;
alert(point.x+" ; "+point.y);

constructor and prototype

function point(x,y)
{
    this.x = x;
    this.y = y;
}

point.prototype = {

    description : "this is a point",

    toString: function()
    {
        return this.x+" : "+this.y;
    }
}

singleton

function bdd() {
}

bdd.prototype = {
instance : null,

getInstance : function()
{
 if (!bdd.prototype.instance)
 bdd.prototype.instance = new bdd();
 return bdd.prototype.instance;
},

tab : ["toto",
       "tata"]
}

var k = bdd.prototype.getInstance();
alert(k.tab[1]); //tata

SOAP

// SOAP params
var entree = "Hello";
var params = new Array();
params[0] = new SOAPParameter(entree,"toto");
var soapCall = new SOAPCall();
soapCall.transportURI = "http://localhost/4DSOAP/";
soapCall.actionURI = "'SOAP#testSOAP'";
/*
void encode (short version,AString methodName ,AString targetObjectURI,
int headerBlockCount,nsISOAPHeaderBlock headerBlocks,int parameterCount,nsISOAPParameter parameters) 
*/
soapCall.encode(SOAPCall.VERSION_1_1, "testSOAP", "http://www.4d.com/namespace/default", 0, null, params.length, params);
var response = soapCall.invoke();
var fault = response.fault;
if (fault != null) 
{
    alert("code erreur : "+fault.faultCode+"; description : "+fault.faultString);
}
else
{
    var reponses = response.getParameters(false,{});
    for (var i = 0; i < reponses.length; i++)
    {
        alert(reponses[i].value); // Hello
    } 
}
POST /4DSOAP/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Content-Type: text/xml; charset=UTF-8
SOAPAction: 'SOAP#testSOAP'
Content-Length: 435
Pragma: no-cache
<env:Envelope     xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" 
                xmlns:enc="http://schemas.xmlsoap.org/soap/encoding/" 
                env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" 
                xmlns:xs="http://www.w3.org/1999/XMLSchema" 
                xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">
<env:Header/>
<env:Body>
<testSOAP xmlns="http://www.4d.com/namespace/default">
<toto xsi:type="xs:string">Hello</toto>
</testSOAP>
</env:Body>
</env:Envelope>

Find the path to the chrome folder

var file = Components.classes["@mozilla.org/file/directory_service;1"]
                      .getService(Components.interfaces.nsIProperties)
                      .get("AChrom", Components.interfaces.nsIFile);
alert(file.path);

Play sound

var son = Components.classes["@mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);
son.init();

var Player = {
  getSound: function(url) {
    if( url=='beep' ) { return 'beep'; }
    try {
      var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
      file.initWithPath(url);
      if(!file.exists())return null;
      return ioService.newFileURI(file);
    } catch(e) {
      try {
        if(url == "")return null;
        return ioService.newURI(url, null, null);   // currently, without existence testing
      } catch(e2) {
        writeLog("Player :"+e2);
        return null;
      }
    }
  },

  play: function(url) {
      if(url=='beep') son.beep();
      else son.play( this.getSound(url) );
  }
};

Work with listbox

file.xul contains a empty listbox like this one :

listbox
<listbox rows="15" id="tabSites" >
    <listcols>
    <listcol flex="1" />
    <splitter class="tree-splitter" />
    <listcol flex="1" />
    <splitter class="tree-splitter" />
    <listcol flex="1" />
    <splitter class="tree-splitter" />
    <listcol flex="1" />    
    </listcols>
    <listhead>
    <listheader label="URL" />
    <listheader label="TYPE" />
    <listheader label="CREDIT" />
    <listheader label="ACTION" />
    </listhead>

    <!-- we will add dynamically this listitem in file.js
    <listitem >
    <listcell label="http://www.excessivetraffic.com/login2.php?ref=1" type="checkbox" checked="true" />
    <listcell label="manual" />
    <listcell label="0" />
    <listcell label="sleeping..." />
    </listitem> -->

</listbox>

file.js

var listBox = document.getElementById("tabSites");
var li = document.createElement("listitem");            
var lc1 = document.createElement("listcell");
lc1.setAttribute("label","http://www.excessivetraffic.com/login2.php?ref=1");
lc1.setAttribute("type","checkbox");
lc1.setAttribute("checked","true");
li.appendChild(lc1);
var lc2 = document.createElement("listcell");
lc2.setAttribute("label","manual");
li.appendChild(lc2);
var lc3 = document.createElement("listcell");
lc3.setAttribute("label","0");
li.appendChild(lc3);
var lc4 = document.createElement("listcell");
lc4.setAttribute("label","sleeping...");
li.appendChild(lc4);
listBox.appendChild(li);

Delete all listcell of the listitem :

while(li.firstChild) 
    li.removeChild(li.firstChild);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License