xmpp4js - Code Samples

Information

In addition to these snippets, check out the SimpleClient demo in the xmpp4js-launcher project.

Core

Create a connection

var con = new JabberConnection( "/http-bind/", "soashable.com" );
con.beginSession();

Close a connection

con.endSession();

Login

con.authenticateMd5( "username", "password", "resource" );

Register

var reg = new Packet.Registration();
reg.setNode( "myjid" );
reg.setPassword( "mypass" );
reg.setEmail( "somebody@somewhere.com" );
reg.setName( "My Name" );

con.send( reg );

Send an IM

var msg = new Packet.Message("somebody@somewhere.com", "hello");
con.send( msg );

Use Chat Manager

var cm = Xmpp4Js.Chat.ChatManager.getInstanceFor( con );

cm.setOptions({
    ignoreThread: true, // useful for legacy networks (AIM)
    ignoreResource: true 
});

cm.on({
    scope : this,
    chatStarted : onChatStarted,
    messageReceived : onChatMessageReceived
});

function onChatStarted(chat) {
    alert( "Chat with "+chat.getParticipant()+" started." );
}

function onChatMessageReceived(chat, messagePacket) {
    alert( "New message from "+messagePacket.getFrom()+": "+messagePacket.getBody() );
}

function sendMessage(to, message) {
    var chat = null;
    try {
        chat = chatManager.findBestChat( to );
    } catch(e) {
        chat = chatManager.createChat( to );
    }
    
    var messagePacket = new Xmpp4Js.Packet.Message( to, "normal", message );
    chat.sendMessage( messagePacket );
}

Pause / Resume a connection


// this assumes ExtJs is present for the state manager. what 
// actually needs to happen is an x-domain state manager needs
// to be implemented so that state can carry across domains.

// setup
LOGIN = "test";
PASSWORD = "test";
SEND_MSG_TO = "harlan@soashable.com";
BOSH_TRANSPORT = Xmpp4Js.Transport.Script;
BOSH_ENDPOINT = "http://bosh*.soashable.com:7070/http-bind/";

Ext.state.Manager.setProvider( new Ext.state.CookieProvider() );

// 1, 4
sp = new Xmpp4Js.Packet.StanzaProvider();
sp.registerDefaultProviders();
con = new Xmpp4Js.Connection({transport: {clazz: BOSH_TRANSPORT,endpoint:BOSH_ENDPOINT,useKeys:true},stanzaProvider:sp});
con.on( "pause", function(pauseStruct) { 
  console.dir( pauseStruct ); 
  Ext.state.Manager.set( "pauseStruct", pauseStruct );
});
con.on( "resume", function(pauseStruct) {
  con.send( new Xmpp4Js.Packet.Message( SEND_MSG_TO, "normal", "yoooo I'm alive" ) );
});
con.on( "connect", function() { 
  loginFlow = new Xmpp4Js.Workflow.Login({con:con});
  loginFlow.on("success", function() {
    con.send( new Xmpp4Js.Packet.Presence() );
  } );
  loginFlow.start( "plaintext", LOGIN, PASSWORD );
});

// 2
con.connect("soashable.com");

// 3 - pause for up to 120 seconds. at this point you can reload the page.
con.pause( 120 );

// 5 - you should receive an IM
ps = Ext.state.Manager.get( "pauseStruct" );
con.resume( ps );
    

Privacy, Presence

Change my presence

var pres = new Packet.Presence( "available", "dnd" );

Change my presence for only a specific buddy

var pres = new Packet.Presence( "available", "dnd" );
pres.setTo( "buddy@soashable.com" );

Capture others' presence

con.addPacketListener( function(presence) {
    var from = presence.getFrom();
    var type = presence.getType();
    var status = presence.getStatus();
    var awayMsg = presence.getShow();
    if( type == "available" ) {
      alert( from + " is " + status + "; show=" + awayMsg );
    } else {
      alert( from + " is offline." );
    }
}, new PacketClassFilter( Packet.Presence ) );

Add a buddy

var roster = con.getRoster();
roster.createEntry( "mybuddy@soashable.com", "My Buddy", ["group a", "group b"] );

Remove a buddy

... there is no way right now. ouch...

Confirm/Deny a request to be added as a buddy

con.addPacketListener( function(presence) {
    if( presence.getType() == "subscribe" ) {
      var allowed = confirm( "Do you want to let " + presence.getTo() + " subscribe to your presence?");
      var outPres = new Packet.Presence( "subscribed" );
      outPres.setTo( presence.getFrom() );
      con.send( outPres );
    }
}, new PacketClassFilter( Packet.Presence ) );

Events, Listeners

Be notified of message events (composing)

con.addPacketListener(
    function(msg) {
      // load extensions that are present in the packet using our ExtensionProvider
      msg.loadExtensions(extensionProvider);

      var msgEvent = msg.getExtension( MessageEventExtension.XMLNS );
      alert( "Message Event: " + msg.getTo() + " - " + msgEvent .getEvent() );

    }, 
    // capture only Message packets with MessageEventExtension
    new AndFilter(
      new PacketClassFilter( Packet.Message ), 
      new ExtensionFilter( MessageEventExtension.XMLNS )
    ) 
);

Respond to version requests

con.addPacketListener( function(iq) {
    var versionIq = new Packet.IQ( iq.getFrom(), "set", "jabber:iq:version" );
    versionIq.getQuery().textContent = "Rockin' Jabber Client";
    con.send( versionIq );
}, new IQQueryNSFilter ( "jabber:iq:version" ) );

Extensions

Sign in to AIM

TransportHelper.registerForAim( "aim.im.soashable.com", "screen name", "password" );

-or-

var reg = new Packet.Registration();
reg.setTo( "aim.soashable.com" );
reg.setNode( "aimscreenname" );
reg.setPassword( "mypass" );

con.send( reg );

Store private data

var ds = con.getDataStorage();
ds.set( "mycompany:greeting", "Hello", "greeting" );

Retrieve private data

var ds = con.getDataStorage();
ds.get( "mycompany:greeting", function(responseNodes ) {
    var greeting = responseNodes[0].textContent;
    alert( greeting );
}, "greeting" );

Conference

Join a Multi-User Chat (MUC)

var extProvider = ...;
var mucMan = MucManager.getInstanceFor( con, "conference.soashable.com", extProvider );

// get info about a room and create a state to act with
var room = mucMan.getRoom( "soashable" ).createState();

// join with the nick "harlan2"
room.join( "harlan2" );

Get the status of a Join

// use extjs's Ext.util.Observable for registering events
room.on({
  join: function(room, participant, packet) { },
  error: function(room, participant, packet) {
    console.dirxml( packet.getExtension( ErrorExtension.XMLNS ).getNode() );
  },
});

room.join( "harlan2" );

Send Message to a MUC

room.sendText( "Hello, MUC!" );

List Occupants

// getting participants happens asynchronously, so it
// does NOT simply return a list.
room.getParticipants(function(room, participants) {
    console.dir( participants );
});

Leave a MUC

room.part();

Getting a list of MUCs

mucMan.getRoomList(function(mucMan, rooms) {
    console.dir( rooms );
});

About xmpp4js

xmpp4js is an xmpp connection library for Javascript. It is written with a heavy emphasis on resuability and extensibility, and is naturally heavilly tested.

About Xmpp4Js

Developer Docs

Project Documentation

Powered By