help with Firefox extension

Posted by Johnny Grass on Stack Overflow See other posts from Stack Overflow or by Johnny Grass
Published on 2011-01-15T19:52:05Z Indexed on 2011/01/17 16:53 UTC
Read the original article Hit count: 359

I'm writing a Firefox extension that creates a socket server which will output the active tab's URL when a client makes a connection to it. I have the following code in my javascript file:

var serverSocket;

function startServer()
{
    var listener =
    {
        onSocketAccepted : function(socket, transport)
        {
            try {
                var outputString = gBrowser.currentURI.spec + "\n";
                var stream = transport.openOutputStream(0,0,0);
                stream.write(outputString,outputString.length);
                stream.close();
            } catch(ex2){ dump("::"+ex2); }
        },

        onStopListening : function(socket, status){}
    };

    try {
        serverSocket = Components.classes["@mozilla.org/network/server-socket;1"]
        .createInstance(Components.interfaces.nsIServerSocket);

        serverSocket.init(7055,true,-1);
        serverSocket.asyncListen(listener);
   } catch(ex){ dump(ex); }

   document.getElementById("status").value = "Started";
}

startServer();

As it is, it works for multiple tabs in a single window. If I open multiple windows, it ignores the additional windows. I think it is creating a server socket for each window, but since they are using the same port, the additional sockets fail to initialize. I need it to create a server socket when the browser launches and continue running when I close the windows (Mac OS X). As it is, when I close a window but Firefox remains running, the socket closes and I have to restart firefox to get it up an running. How do I go about that?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about sockets