strophe.js

A JavaScript library for XMPP BOSH/XMPP over Websocket.

This is the JavaScript version of the Strophe library.  Since JavaScript had no facilities for persistent TCP connections, this library uses Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate a persistent, stateful, two-way connection to an XMPP server.  More information on BOSH can be found in XEP 124.

This version of Strophe also works with WebSockets.  For more information on XMPP-over WebSocket see this RFC draft: http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00

Summary
strophe.jsA JavaScript library for XMPP BOSH/XMPP over Websocket.
Functions
$buildCreate a Strophe.Builder.
$msgCreate a Strophe.Builder with a <message/> element as the root.
$iqCreate a Strophe.Builder with an <iq/> element as the root.
$presCreate a Strophe.Builder with a <presence/> element as the root.
StropheAn object container for all Strophe library functions.
Constants
VERSIONThe version of the Strophe library.
XMPP Namespace ConstantsCommon namespace constants from the XMPP RFCs and XEPs.
XHTML_IM Namespacecontains allowed tags, tag attributes, and css properties.
Connection Status ConstantsConnection status constants for use by the connection handler callback.
Log Level ConstantsLogging level indicators.
Functions
addNamespaceThis function is used to extend the current namespaces in Strophe.NS.
forEachChildMap a function over some or all child elements of a given element.
isTagEqualCompare an element’s tag name with a string.
xmlGeneratorGet the DOM document to generate elements.
xmlElementCreate an XML DOM element.
xmlescapeExcapes invalid xml characters.
xmlTextNodeCreates an XML DOM text node.
xmlHtmlNodeCreates an XML DOM html node.
getTextGet the concatenation of all text children of an element.
copyElementCopy an XML DOM element.
createHtmlCopy an HTML DOM element into an XML DOM.
escapeNodeEscape the node part (also called local part) of a JID.
unescapeNodeUnescape a node part (also called local part) of a JID.
getNodeFromJidGet the node portion of a JID String.
getDomainFromJidGet the domain portion of a JID String.
getResourceFromJidGet the resource portion of a JID String.
getBareJidFromJidGet the bare JID from a JID String.
logUser overrideable logging function.
debugLog a message at the Strophe.LogLevel.DEBUG level.
infoLog a message at the Strophe.LogLevel.INFO level.
warnLog a message at the Strophe.LogLevel.WARN level.
errorLog a message at the Strophe.LogLevel.ERROR level.
fatalLog a message at the Strophe.LogLevel.FATAL level.
serializeRender a DOM element and all descendants to a String.
addConnectionPluginExtends the Strophe.Connection object with the given plugin.
Strophe.BuilderXML DOM builder.
Functions
Strophe.BuilderCreate a Strophe.Builder object.
treeReturn the DOM tree.
toStringSerialize the DOM tree to a String.
upMake the current parent element the new current element.
attrsAdd or modify attributes of the current element.
cAdd a child to the current element and make it the new current element.
cnodeAdd a child to the current element and make it the new current element.
tAdd a child text element.
hReplace current element contents with the HTML passed in.
Strophe.ConnectionXMPP Connection manager.
Functions
Strophe.ConnectionCreate and initialize a Strophe.Connection object.
resetReset the connection.
pausePause the request manager.
resumeResume the request manager.
getUniqueIdGenerate a unique ID for use in <iq/> elements.
connectStarts the connection process.
Variables
authzidAuthorization identity.
authcidAuthentication identity (User name).
passAuthentication identity (User password).
servtypeDigest MD5 compatibility.
Functions
attachAttach to an already created and authenticated BOSH session.
xmlInputUser overrideable function that receives XML data coming into the connection.
xmlOutputUser overrideable function that receives XML data sent to the connection.
rawInputUser overrideable function that receives raw data coming into the connection.
rawOutputUser overrideable function that receives raw data sent to the connection.
sendSend a stanza.
flushImmediately send any pending outgoing data.
sendIQHelper function to send IQ stanzas.
addTimedHandlerAdd a timed handler to the connection.
deleteTimedHandlerDelete a timed handler for a connection.
addHandlerAdd a stanza handler for the connection.
deleteHandlerDelete a stanza handler for a connection.
disconnectStart the graceful disconnection process.
authenticateSet up authentication
Strophe.SASLMechanismencapsulates SASL authentication mechanisms.
Variables
priorityDetermines which SASLMechanism is chosen for authentication (Higher is better).
Functions
testChecks if mechanism able to run.
Constants
SASL mechanismsAvailable authentication mechanisms
Strophe.BoshPrivate helper class that handles BOSH Connections
Files
bosh.jsA JavaScript library to enable BOSH in Strophejs.
Variables
stripBOSH-Connections will have all stanzas wrapped in a <body> tag when passed to Strophe.Connection.xmlInput or Strophe.Connection.xmlOutput.
Strophe.WebSocketPrivate helper class that handles WebSocket Connections
Files
websocket.jsA JavaScript library to enable XMPP over Websocket in Strophejs.

Functions

$build

function $build(name,
attrs)

Create a Strophe.Builder.  This is an alias for ‘new Strophe.Builder(name, attrs)’.

Parameters

(String) nameThe root element name.
(Object) attrsThe attributes for the root element in object notation.

Returns

A new Strophe.Builder object.

$msg

function $msg(attrs)

Create a Strophe.Builder with a <message/> element as the root.

Parmaeters

(Object) attrsThe <message/> element attributes in object notation.

Returns

A new Strophe.Builder object.

$iq

function $iq(attrs)

Create a Strophe.Builder with an <iq/> element as the root.

Parameters

(Object) attrsThe <iq/> element attributes in object notation.

Returns

A new Strophe.Builder object.

$pres

function $pres(attrs)

Create a Strophe.Builder with a <presence/> element as the root.

Parameters

(Object) attrsThe <presence/> element attributes in object notation.

Returns

A new Strophe.Builder object.

Strophe

An object container for all Strophe library functions.

This class is just a container for all the objects and constants used in the library.  It is not meant to be instantiated, but to provide a namespace for library objects, constants, and functions.

Summary
Constants
VERSIONThe version of the Strophe library.
XMPP Namespace ConstantsCommon namespace constants from the XMPP RFCs and XEPs.
XHTML_IM Namespacecontains allowed tags, tag attributes, and css properties.
Connection Status ConstantsConnection status constants for use by the connection handler callback.
Log Level ConstantsLogging level indicators.
Functions
addNamespaceThis function is used to extend the current namespaces in Strophe.NS.
forEachChildMap a function over some or all child elements of a given element.
isTagEqualCompare an element’s tag name with a string.
xmlGeneratorGet the DOM document to generate elements.
xmlElementCreate an XML DOM element.
xmlescapeExcapes invalid xml characters.
xmlTextNodeCreates an XML DOM text node.
xmlHtmlNodeCreates an XML DOM html node.
getTextGet the concatenation of all text children of an element.
copyElementCopy an XML DOM element.
createHtmlCopy an HTML DOM element into an XML DOM.
escapeNodeEscape the node part (also called local part) of a JID.
unescapeNodeUnescape a node part (also called local part) of a JID.
getNodeFromJidGet the node portion of a JID String.
getDomainFromJidGet the domain portion of a JID String.
getResourceFromJidGet the resource portion of a JID String.
getBareJidFromJidGet the bare JID from a JID String.
logUser overrideable logging function.
debugLog a message at the Strophe.LogLevel.DEBUG level.
infoLog a message at the Strophe.LogLevel.INFO level.
warnLog a message at the Strophe.LogLevel.WARN level.
errorLog a message at the Strophe.LogLevel.ERROR level.
fatalLog a message at the Strophe.LogLevel.FATAL level.
serializeRender a DOM element and all descendants to a String.
addConnectionPluginExtends the Strophe.Connection object with the given plugin.

Constants

VERSION

The version of the Strophe library.  Unreleased builds will have a version of head-HASH where HASH is a partial revision.

XMPP Namespace Constants

Common namespace constants from the XMPP RFCs and XEPs.

NS.HTTPBINDHTTP BIND namespace from XEP 124.
NS.BOSHBOSH namespace from XEP 206.
NS.CLIENTMain XMPP client namespace.
NS.AUTHLegacy authentication namespace.
NS.ROSTERRoster operations namespace.
NS.PROFILEProfile namespace.
NS.DISCO_INFOService discovery info namespace from XEP 30.
NS.DISCO_ITEMSService discovery items namespace from XEP 30.
NS.MUCMulti-User Chat namespace from XEP 45.
NS.SASLXMPP SASL namespace from RFC 3920.
NS.STREAMXMPP Streams namespace from RFC 3920.
NS.BINDXMPP Binding namespace from RFC 3920.
NS.SESSIONXMPP Session namespace from RFC 3920.
NS.XHTML_IMXHTML-IM namespace from XEP 71.
NS.XHTMLXHTML body namespace from XEP 71.

XHTML_IM Namespace

contains allowed tags, tag attributes, and css properties.  Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset.  See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended allowed tags and their attributes.

Connection Status Constants

Connection status constants for use by the connection handler callback.

Status.ERRORAn error has occurred
Status.CONNECTINGThe connection is currently being made
Status.CONNFAILThe connection attempt failed
Status.AUTHENTICATINGThe connection is authenticating
Status.AUTHFAILThe authentication attempt failed
Status.CONNECTEDThe connection has succeeded
Status.DISCONNECTEDThe connection has been terminated
Status.DISCONNECTINGThe connection is currently being terminated
Status.ATTACHEDThe connection has been attached

Log Level Constants

Logging level indicators.

LogLevel.DEBUGDebug output
LogLevel.INFOInformational output
LogLevel.WARNWarnings
LogLevel.ERRORErrors
LogLevel.FATALFatal errors

Functions

addNamespace

addNamespace: function (name,
value)

This function is used to extend the current namespaces in Strophe.NS.  It takes a key and a value with the key being the name of the new namespace, with its actual value.  For example: Strophe.addNamespace(‘PUBSUB’, “http://jabber.org/protocol/pubsub”);

Parameters

(String) nameThe name under which the namespace will be referenced under Strophe.NS
(String) valueThe actual namespace.

forEachChild

forEachChild: function (elem,
elemName,
func)

Map a function over some or all child elements of a given element.

This is a small convenience function for mapping a function over some or all of the children of an element.  If elemName is null, all children will be passed to the function, otherwise only children whose tag names match elemName will be passed.

Parameters

(XMLElement) elemThe element to operate on.
(String) elemNameThe child element tag name filter.
(Function) funcThe function to apply to each child.  This function should take a single argument, a DOM element.

isTagEqual

isTagEqual: function (el,
name)

Compare an element’s tag name with a string.

This function is case insensitive.

Parameters

(XMLElement) elA DOM element.
(String) nameThe element name.

Returns

true if the element’s tag name matches el, and false otherwise.

xmlGenerator

xmlGenerator: function ()

Get the DOM document to generate elements.

Returns

The currently used DOM document.

xmlElement

xmlElement: function (name)

Create an XML DOM element.

This function creates an XML DOM element correctly across all implementations.  Note that these are not HTML DOM elements, which aren’t appropriate for XMPP stanzas.

Parameters

(String) nameThe name for the element.
(Array|Object) attrsAn optional array or object containing key/value pairs to use as element attributes.  The object should be in the format {‘key’: ‘value’} or {key: ‘value’}.  The array should have the format [[‘key1’, ‘value1’], [‘key2’, ‘value2’]].
(String) textThe text child data for the element.

Returns

A new XML DOM element.

xmlescape

xmlescape: function(text)

Excapes invalid xml characters.

Parameters

(String) texttext to escape.

Returns

Escaped text.

xmlTextNode

xmlTextNode: function (text)

Creates an XML DOM text node.

Provides a cross implementation version of document.createTextNode.

Parameters

(String) textThe content of the text node.

Returns

A new XML DOM text node.

xmlHtmlNode

xmlHtmlNode: function (html)

Creates an XML DOM html node.

Parameters

(String) htmlThe content of the html node.

Returns

A new XML DOM text node.

getText

getText: function (elem)

Get the concatenation of all text children of an element.

Parameters

(XMLElement) elemA DOM element.

Returns

A String with the concatenated text of all text element children.

copyElement

copyElement: function (elem)

Copy an XML DOM element.

This function copies a DOM element and all its descendants and returns the new copy.

Parameters

(XMLElement) elemA DOM element.

Returns

A new, copied DOM element tree.

createHtml

createHtml: function (elem)

Copy an HTML DOM element into an XML DOM.

This function copies a DOM element and all its descendants and returns the new copy.

Parameters

(HTMLElement) elemA DOM element.

Returns

A new, copied DOM element tree.

escapeNode

escapeNode: function (node)

Escape the node part (also called local part) of a JID.

Parameters

(String) nodeA node (or local part).

Returns

An escaped node (or local part).

unescapeNode

unescapeNode: function (node)

Unescape a node part (also called local part) of a JID.

Parameters

(String) nodeA node (or local part).

Returns

An unescaped node (or local part).

getNodeFromJid

getNodeFromJid: function (jid)

Get the node portion of a JID String.

Parameters

(String) jidA JID.

Returns

A String containing the node.

getDomainFromJid

getDomainFromJid: function (jid)

Get the domain portion of a JID String.

Parameters

(String) jidA JID.

Returns

A String containing the domain.

getResourceFromJid

getResourceFromJid: function (jid)

Get the resource portion of a JID String.

Parameters

(String) jidA JID.

Returns

A String containing the resource.

getBareJidFromJid

getBareJidFromJid: function (jid)

Get the bare JID from a JID String.

Parameters

(String) jidA JID.

Returns

A String containing the bare JID.

log

User overrideable logging function.

This function is called whenever the Strophe library calls any of the logging functions.  The default implementation of this function does nothing.  If client code wishes to handle the logging messages, it should override this with

Strophe.log = function (level, msg) {
  (user code here)
};

Please note that data sent and received over the wire is logged via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().

The different levels and their meanings are

DEBUGMessages useful for debugging purposes.
INFOInformational messages.  This is mostly information like ‘disconnect was called’ or ‘SASL auth succeeded’.
WARNWarnings about potential problems.  This is mostly used to report transient connection errors like request timeouts.
ERRORSome error occurred.
FATALA non-recoverable fatal error occurred.

Parameters

(Integer) levelThe log level of the log message.  This will be one of the values in Strophe.LogLevel.
(String) msgThe log message.

debug

debug: function(msg)

Log a message at the Strophe.LogLevel.DEBUG level.

Parameters

(String) msgThe log message.

info

info: function (msg)

Log a message at the Strophe.LogLevel.INFO level.

Parameters

(String) msgThe log message.

warn

warn: function (msg)

Log a message at the Strophe.LogLevel.WARN level.

Parameters

(String) msgThe log message.

error

error: function (msg)

Log a message at the Strophe.LogLevel.ERROR level.

Parameters

(String) msgThe log message.

fatal

fatal: function (msg)

Log a message at the Strophe.LogLevel.FATAL level.

Parameters

(String) msgThe log message.

serialize

serialize: function (elem)

Render a DOM element and all descendants to a String.

Parameters

(XMLElement) elemA DOM element.

Returns

The serialized element tree as a String.

addConnectionPlugin

addConnectionPlugin: function (name,
ptype)

Extends the Strophe.Connection object with the given plugin.

Parameters

(String) nameThe name of the extension.
(Object) ptypeThe plugin’s prototype.

Strophe.Builder

XML DOM builder.

This object provides an interface similar to JQuery but for building DOM element easily and rapidly.  All the functions except for toString() and tree() return the object, so calls can be chained.  Here’s an example using the $iq() builder helper.

$iq({to: 'you', from: 'me', type: 'get', id: '1'})
    .c('query', {xmlns: 'strophe:example'})
    .c('example')
    .toString()

The above generates this XML fragment

<iq to='you' from='me' type='get' id='1'>
  <query xmlns='strophe:example'>
    <example/>
  </query>
</iq>

The corresponding DOM manipulations to get a similar fragment would be a lot more tedious and probably involve several helper variables.

Since adding children makes new operations operate on the child, up() is provided to traverse up the tree.  To add two children, do

builder.c('child1', ...).up().c('child2', ...)

The next operation on the Builder will be relative to the second child.

Summary
Functions
Strophe.BuilderCreate a Strophe.Builder object.
treeReturn the DOM tree.
toStringSerialize the DOM tree to a String.
upMake the current parent element the new current element.
attrsAdd or modify attributes of the current element.
cAdd a child to the current element and make it the new current element.
cnodeAdd a child to the current element and make it the new current element.
tAdd a child text element.
hReplace current element contents with the HTML passed in.

Functions

Strophe.Builder

Strophe.Builder = function (name,
attrs)

Create a Strophe.Builder object.

The attributes should be passed in object notation.  For example

var b = new Builder('message', {to: 'you', from: 'me'});

or

var b = new Builder('messsage', {'xml:lang': 'en'});

Parameters

(String) nameThe name of the root element.
(Object) attrsThe attributes for the root element in object notation.

Returns

A new Strophe.Builder.

tree

tree: function ()

Return the DOM tree.

This function returns the current DOM tree as an element object.  This is suitable for passing to functions like Strophe.Connection.send().

Returns

The DOM tree as a element object.

toString

toString: function ()

Serialize the DOM tree to a String.

This function returns a string serialization of the current DOM tree.  It is often used internally to pass data to a Strophe.Request object.

Returns

The serialized DOM tree in a String.

up

up: function ()

Make the current parent element the new current element.

This function is often used after c() to traverse back up the tree.  For example, to add two children to the same element

builder.c('child1', {}).up().c('child2', {});

Returns

The Stophe.Builder object.

attrs

attrs: function (moreattrs)

Add or modify attributes of the current element.

The attributes should be passed in object notation.  This function does not move the current element pointer.

Parameters

(Object) moreattrsThe attributes to add/modify in object notation.

Returns

The Strophe.Builder object.

c

c: function (name,
attrs,
text)

Add a child to the current element and make it the new current element.

This function moves the current element pointer to the child, unless text is provided.  If you need to add another child, it is necessary to use up() to go back to the parent in the tree.

Parameters

(String) nameThe name of the child.
(Object) attrsThe attributes of the child in object notation.
(String) textThe text to add to the child.

Returns

The Strophe.Builder object.

cnode

cnode: function (elem)

Add a child to the current element and make it the new current element.

This function is the same as c() except that instead of using a name and an attributes object to create the child it uses an existing DOM element object.

Parameters

(XMLElement) elemA DOM element.

Returns

The Strophe.Builder object.

t

t: function (text)

Add a child text element.

This does not make the child the new current element since there are no children of text elements.

Parameters

(String) textThe text data to append to the current element.

Returns

The Strophe.Builder object.

h

h: function (html)

Replace current element contents with the HTML passed in.

This does not make the child the new current element

Parameters

(String) htmlThe html to insert as contents of current element.

Returns

The Strophe.Builder object.

Strophe.Connection

XMPP Connection manager.

This class is the main part of Strophe.  It manages a BOSH connection to an XMPP server and dispatches events to the user callbacks as data arrives.  It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1 and legacy authentication.

After creating a Strophe.Connection object, the user will typically call connect() with a user supplied callback to handle connection level events like authentication failure, disconnection, or connection complete.

The user will also have several event handlers defined by using addHandler() and addTimedHandler().  These will allow the user code to respond to interesting stanzas or do something periodically with the connection.  These handlers will be active once authentication is finished.

To send data to the connection, use send().

Summary
Functions
Strophe.ConnectionCreate and initialize a Strophe.Connection object.
resetReset the connection.
pausePause the request manager.
resumeResume the request manager.
getUniqueIdGenerate a unique ID for use in <iq/> elements.
connectStarts the connection process.
Variables
authzidAuthorization identity.
authcidAuthentication identity (User name).
passAuthentication identity (User password).
servtypeDigest MD5 compatibility.
Functions
attachAttach to an already created and authenticated BOSH session.
xmlInputUser overrideable function that receives XML data coming into the connection.
xmlOutputUser overrideable function that receives XML data sent to the connection.
rawInputUser overrideable function that receives raw data coming into the connection.
rawOutputUser overrideable function that receives raw data sent to the connection.
sendSend a stanza.
flushImmediately send any pending outgoing data.
sendIQHelper function to send IQ stanzas.
addTimedHandlerAdd a timed handler to the connection.
deleteTimedHandlerDelete a timed handler for a connection.
addHandlerAdd a stanza handler for the connection.
deleteHandlerDelete a stanza handler for a connection.
disconnectStart the graceful disconnection process.
authenticateSet up authentication

Functions

Strophe.Connection

Strophe.Connection = function (service,
options)

Create and initialize a Strophe.Connection object.

The transport-protocol for this connection will be chosen automatically based on the given service parameter.  URLs starting with “ws://” or “wss://” will use WebSockets, URLs starting with “http://”, “https://” or without a protocol will use BOSH.

To make Strophe connect to the current host you can leave out the protocol and host part and just pass the path, e.g.

var conn = new Strophe.Connection("/http-bind/");

WebSocket options

If you want to connect to the current host with a WebSocket connection you can tell Strophe to use WebSockets through a “protocol” attribute in the optional options parameter.  Valid values are “ws” for WebSocket and “wss” for Secure WebSocket.  So to connect to “wss://CURRENT_HOSTNAME/xmpp-websocket” you would call

var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"});

Note that relative URLs NOT starting with a “/” will also include the path of the current site.

Also because downgrading security is not permitted by browsers, when using relative URLs both BOSH and WebSocket connections will use their secure variants if the current connection to the site is also secure (https).

BOSH options

by adding “sync” to the options, you can control if requests will be made synchronously or not.  The default behaviour is asynchronous.  If you want to make requests synchronous, make “sync” evaluate to true:

var conn = new Strophe.Connection("/http-bind/", {sync: true});

You can also toggle this on an already established connection:

conn.options.sync = true;

Parameters

(String) serviceThe BOSH or WebSocket service URL.
(Object) optionsA hash of configuration options

Returns

A new Strophe.Connection object.

reset

reset: function ()

Reset the connection.

This function should be called after a connection is disconnected before that connection is reused.

pause

pause: function ()

Pause the request manager.

This will prevent Strophe from sending any more requests to the server.  This is very useful for temporarily pausing BOSH-Connections while a lot of send() calls are happening quickly.  This causes Strophe to send the data in a single request, saving many request trips.

resume

resume: function ()

Resume the request manager.

This resumes after pause() has been called.

getUniqueId

getUniqueId: function (suffix)

Generate a unique ID for use in <iq/> elements.

All <iq/> stanzas are required to have unique id attributes.  This function makes creating these easy.  Each connection instance has a counter which starts from zero, and the value of this counter plus a colon followed by the suffix becomes the unique id.  If no suffix is supplied, the counter is used as the unique id.

Suffixes are used to make debugging easier when reading the stream data, and their use is recommended.  The counter resets to 0 for every new connection for the same reason.  For connections to the same server that authenticate the same way, all the ids should be the same, which makes it easy to see changes.  This is useful for automated testing as well.

Parameters

(String) suffixA optional suffix to append to the id.

Returns

A unique string to be used for the id attribute.

connect

connect: function (jid,
pass,
callback,
wait,
hold,
route)

Starts the connection process.

As the connection process proceeds, the user supplied callback will be triggered multiple times with status updates.  The callback should take two arguments - the status code and the error condition.

The status code will be one of the values in the Strophe.Status constants.  The error condition will be one of the conditions defined in RFC 3920 or the condition ‘strophe-parsererror’.

The Parameters wait, hold and route are optional and only relevant for BOSH connections.  Please see XEP 124 for a more detailed explanation of the optional parameters.

Parameters

(String) jidThe user’s JID.  This may be a bare JID, or a full JID.  If a node is not supplied, SASL ANONYMOUS authentication will be attempted.
(String) passThe user’s password.
(Function) callbackThe connect callback function.
(Integer) waitThe optional HTTPBIND wait value.  This is the time the server will wait before returning an empty result for a request.  The default setting of 60 seconds is recommended.
(Integer) holdThe optional HTTPBIND hold value.  This is the number of connections the server will hold at one time.  This should almost always be set to 1 (the default).
(String) routeThe optional route value.

Variables

authzid

this.authzid

Authorization identity.

authcid

this.authcid

Authentication identity (User name).

pass

this.pass

Authentication identity (User password).

servtype

this.servtype

Digest MD5 compatibility.

Functions

attach

attach: function (jid,
sid,
rid,
callback,
wait,
hold,
wind)

Attach to an already created and authenticated BOSH session.

This function is provided to allow Strophe to attach to BOSH sessions which have been created externally, perhaps by a Web application.  This is often used to support auto-login type features without putting user credentials into the page.

Parameters

(String) jidThe full JID that is bound by the session.
(String) sidThe SID of the BOSH session.
(String) ridThe current RID of the BOSH session.  This RID will be used by the next request.  (Function) callback The connect callback function.
(Integer) waitThe optional HTTPBIND wait value.  This is the time the server will wait before returning an empty result for a request.  The default setting of 60 seconds is recommended.  Other settings will require tweaks to the Strophe.TIMEOUT value.
(Integer) holdThe optional HTTPBIND hold value.  This is the number of connections the server will hold at one time.  This should almost always be set to 1 (the default).
(Integer) windThe optional HTTBIND window value.  This is the allowed range of request ids that are valid.  The default is 5.

xmlInput

User overrideable function that receives XML data coming into the connection.

The default function does nothing.  User code can override this with

Strophe.Connection.xmlInput = function (elem) {
  (user code)
};

Due to limitations of current Browsers’ XML-Parsers the opening and closing <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.

BOSH-Connections will have all stanzas wrapped in a <body> tag.  See Strophe.Bosh.strip if you want to strip this tag.

Parameters

(XMLElement) elemThe XML data received by the connection.

xmlOutput

User overrideable function that receives XML data sent to the connection.

The default function does nothing.  User code can override this with

Strophe.Connection.xmlOutput = function (elem) {
  (user code)
};

Due to limitations of current Browsers’ XML-Parsers the opening and closing <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.

BOSH-Connections will have all stanzas wrapped in a <body> tag.  See Strophe.Bosh.strip if you want to strip this tag.

Parameters

(XMLElement) elemThe XMLdata sent by the connection.

rawInput

User overrideable function that receives raw data coming into the connection.

The default function does nothing.  User code can override this with

Strophe.Connection.rawInput = function (data) {
  (user code)
};

Parameters

(String) dataThe data received by the connection.

rawOutput

User overrideable function that receives raw data sent to the connection.

The default function does nothing.  User code can override this with

Strophe.Connection.rawOutput = function (data) {
  (user code)
};

Parameters

(String) dataThe data sent by the connection.

send

send: function (elem)

Send a stanza.

This function is called to push data onto the send queue to go out over the wire.  Whenever a request is sent to the BOSH server, all pending data is sent and the queue is flushed.

Parameters

(XMLElement | [XMLElement] | Strophe.Builder) elem - The stanza to send.

flush

flush: function ()

Immediately send any pending outgoing data.

Normally send() queues outgoing data until the next idle period (100ms), which optimizes network use in the common cases when several send()s are called in succession. flush() can be used to immediately send all pending data.

sendIQ

sendIQ: function(elem,
callback,
errback,
timeout)

Helper function to send IQ stanzas.

Parameters

(XMLElement) elemThe stanza to send.
(Function) callbackThe callback function for a successful request.
(Function) errbackThe callback function for a failed or timed out request.  On timeout, the stanza will be null.
(Integer) timeoutThe time specified in milliseconds for a timeout to occur.

Returns

The id used to send the IQ.

addTimedHandler

addTimedHandler: function (period,
handler)

Add a timed handler to the connection.

This function adds a timed handler.  The provided handler will be called every period milliseconds until it returns false, the connection is terminated, or the handler is removed.  Handlers that wish to continue being invoked should return true.

Because of method binding it is necessary to save the result of this function if you wish to remove a handler with deleteTimedHandler().

Note that user handlers are not active until authentication is successful.

Parameters

(Integer) periodThe period of the handler.
(Function) handlerThe callback function.

Returns

A reference to the handler that can be used to remove it.

deleteTimedHandler

deleteTimedHandler: function (handRef)

Delete a timed handler for a connection.

This function removes a timed handler from the connection.  The handRef parameter is not the function passed to addTimedHandler(), but is the reference returned from addTimedHandler().

Parameters

(Strophe.TimedHandler) handRefThe handler reference.

addHandler

addHandler: function (handler,
ns,
name,
type,
id,
from,
options)

Add a stanza handler for the connection.

This function adds a stanza handler to the connection.  The handler callback will be called for any stanza that matches the parameters.  Note that if multiple parameters are supplied, they must all match for the handler to be invoked.

The handler will receive the stanza that triggered it as its argument.  The handler should return true if it is to be invoked again; returning false will remove the handler after it returns.

As a convenience, the ns parameters applies to the top level element and also any of its immediate children.  This is primarily to make matching /iq/query elements easy.

The options argument contains handler matching flags that affect how matches are determined.  Currently the only flag is matchBare (a boolean).  When matchBare is true, the from parameter and the from attribute on the stanza will be matched as bare JIDs instead of full JIDs.  To use this, pass {matchBare: true} as the value of options.  The default value for matchBare is false.

The return value should be saved if you wish to remove the handler with deleteHandler().

Parameters

(Function) handlerThe user callback.
(String) nsThe namespace to match.
(String) nameThe stanza name to match.
(String) typeThe stanza type attribute to match.
(String) idThe stanza id attribute to match.
(String) fromThe stanza from attribute to match.
(String) optionsThe handler options

Returns

A reference to the handler that can be used to remove it.

deleteHandler

deleteHandler: function (handRef)

Delete a stanza handler for a connection.

This function removes a stanza handler from the connection.  The handRef parameter is not the function passed to addHandler(), but is the reference returned from addHandler().

Parameters

(Strophe.Handler) handRefThe handler reference.

disconnect

disconnect: function (reason)

Start the graceful disconnection process.

This function starts the disconnection process.  This process starts by sending unavailable presence and sending BOSH body of type terminate.  A timeout handler makes sure that disconnection happens even if the BOSH server does not respond.

The user supplied connection callback will be notified of the progress as this process happens.

Parameters

(String) reasonThe reason the disconnect is occuring.

authenticate

authenticate: function (matched)

Set up authentication

Contiunues the initial connection request by setting up authentication handlers and start the authentication process.

SASL authentication will be attempted if available, otherwise the code will fall back to legacy authentication.

Strophe.SASLMechanism

encapsulates SASL authentication mechanisms.

User code may override the priority for each mechanism or disable it completely.  See priority for information about changing priority and test for informatian on how to disable a mechanism.

By default, all mechanisms are enabled and the priorities are

SCRAM-SHA140
DIGEST-MD530
Plain20
Summary
Variables
priorityDetermines which SASLMechanism is chosen for authentication (Higher is better).
Functions
testChecks if mechanism able to run.
Constants
SASL mechanismsAvailable authentication mechanisms

Variables

priority

this.priority

Determines which SASLMechanism is chosen for authentication (Higher is better).  Users may override this to prioritize mechanisms differently.

In the default configuration the priorities are

SCRAM-SHA140
DIGEST-MD530
Plain20

Example: (This will cause Strophe to choose the mechanism that the server sent first)

Strophe.SASLMD5.priority = Strophe.SASLSHA1.priority;

See SASL mechanisms for a list of available mechanisms.

Functions

test

Checks if mechanism able to run.  To disable a mechanism, make this return false;

To disable plain authentication run

Strophe.SASLPlain.test = function() {
  return false;
}

See SASL mechanisms for a list of available mechanisms.

Parameters

(Strophe.Connection) connectionTarget Connection.

Returns

(Boolean) If mechanism was able to run.

Constants

SASL mechanisms

Available authentication mechanisms

Strophe.SASLAnonymousSASL Anonymous authentication.
Strophe.SASLPlainSASL Plain authentication.
Strophe.SASLMD5SASL Digest-MD5 authentication
Strophe.SASLSHA1SASL SCRAM-SHA1 authentication

Strophe.Bosh

Private helper class that handles BOSH Connections

The Strophe.Bosh class is used internally by Strophe.Connection to encapsulate BOSH sessions.  It is not meant to be used from user’s code.

Summary
Files
bosh.jsA JavaScript library to enable BOSH in Strophejs.
Variables
stripBOSH-Connections will have all stanzas wrapped in a <body> tag when passed to Strophe.Connection.xmlInput or Strophe.Connection.xmlOutput.

Files

bosh.js

A JavaScript library to enable BOSH in Strophejs.

this library uses Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate a persistent, stateful, two-way connection to an XMPP server.  More information on BOSH can be found in XEP 124.

Variables

strip

strip: null

BOSH-Connections will have all stanzas wrapped in a <body> tag when passed to Strophe.Connection.xmlInput or Strophe.Connection.xmlOutput.  To strip this tag, User code can set Strophe.Bosh.strip to “body”:

Strophe.Bosh.prototype.strip = "body";

This will enable stripping of the body tag in both Strophe.Connection.xmlInput and Strophe.Connection.xmlOutput.

Strophe.WebSocket

Private helper class that handles WebSocket Connections

The Strophe.WebSocket class is used internally by Strophe.Connection to encapsulate WebSocket sessions.  It is not meant to be used from user’s code.

Summary
Files
websocket.jsA JavaScript library to enable XMPP over Websocket in Strophejs.

Files

websocket.js

A JavaScript library to enable XMPP over Websocket in Strophejs.

This file implements XMPP over WebSockets for Strophejs.  If a Connection is established with a Websocket url (ws://...)  Strophe will use WebSockets.  For more information on XMPP-over WebSocket see this RFC draft: http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00

WebSocket support implemented by Andreas Guth (andrea.nosp@m.s.guth@rwth-aa.nosp@m.chen.de)

function $build(name,
attrs)
Create a Strophe.Builder.
function $msg(attrs)
Create a Strophe.Builder with a message/ element as the root.
function $iq(attrs)
Create a Strophe.Builder with an iq/ element as the root.
function $pres(attrs)
Create a Strophe.Builder with a presence/ element as the root.
addNamespace: function (name,
value)
This function is used to extend the current namespaces in Strophe.NS.
forEachChild: function (elem,
elemName,
func)
Map a function over some or all child elements of a given element.
isTagEqual: function (el,
name)
Compare an element’s tag name with a string.
xmlGenerator: function ()
Get the DOM document to generate elements.
xmlElement: function (name)
Create an XML DOM element.
xmlescape: function(text)
Excapes invalid xml characters.
xmlTextNode: function (text)
Creates an XML DOM text node.
xmlHtmlNode: function (html)
Creates an XML DOM html node.
getText: function (elem)
Get the concatenation of all text children of an element.
copyElement: function (elem)
Copy an XML DOM element.
createHtml: function (elem)
Copy an HTML DOM element into an XML DOM.
escapeNode: function (node)
Escape the node part (also called local part) of a JID.
unescapeNode: function (node)
Unescape a node part (also called local part) of a JID.
getNodeFromJid: function (jid)
Get the node portion of a JID String.
getDomainFromJid: function (jid)
Get the domain portion of a JID String.
getResourceFromJid: function (jid)
Get the resource portion of a JID String.
getBareJidFromJid: function (jid)
Get the bare JID from a JID String.
debug: function(msg)
Log a message at the Strophe.LogLevel.DEBUG level.
info: function (msg)
Log a message at the Strophe.LogLevel.INFO level.
warn: function (msg)
Log a message at the Strophe.LogLevel.WARN level.
error: function (msg)
Log a message at the Strophe.LogLevel.ERROR level.
fatal: function (msg)
Log a message at the Strophe.LogLevel.FATAL level.
serialize: function (elem)
Render a DOM element and all descendants to a String.
addConnectionPlugin: function (name,
ptype)
Extends the Strophe.Connection object with the given plugin.
Strophe.Builder = function (name,
attrs)
Create a Strophe.Builder object.
tree: function ()
Return the DOM tree.
toString: function ()
Serialize the DOM tree to a String.
up: function ()
Make the current parent element the new current element.
attrs: function (moreattrs)
Add or modify attributes of the current element.
c: function (name,
attrs,
text)
Add a child to the current element and make it the new current element.
cnode: function (elem)
Add a child to the current element and make it the new current element.
t: function (text)
Add a child text element.
h: function (html)
Replace current element contents with the HTML passed in.
Strophe.Connection = function (service,
options)
Create and initialize a Strophe.Connection object.
reset: function ()
Reset the connection.
pause: function ()
Pause the request manager.
resume: function ()
Resume the request manager.
getUniqueId: function (suffix)
Generate a unique ID for use in iq/ elements.
connect: function (jid,
pass,
callback,
wait,
hold,
route)
Starts the connection process.
this.authzid
Authorization identity.
this.authcid
Authentication identity (User name).
this.pass
Authentication identity (User password).
this.servtype
Digest MD5 compatibility.
attach: function (jid,
sid,
rid,
callback,
wait,
hold,
wind)
Attach to an already created and authenticated BOSH session.
send: function (elem)
Send a stanza.
flush: function ()
Immediately send any pending outgoing data.
sendIQ: function(elem,
callback,
errback,
timeout)
Helper function to send IQ stanzas.
addTimedHandler: function (period,
handler)
Add a timed handler to the connection.
deleteTimedHandler: function (handRef)
Delete a timed handler for a connection.
addHandler: function (handler,
ns,
name,
type,
id,
from,
options)
Add a stanza handler for the connection.
deleteHandler: function (handRef)
Delete a stanza handler for a connection.
disconnect: function (reason)
Start the graceful disconnection process.
authenticate: function (matched)
Set up authentication
this.priority
Determines which SASLMechanism is chosen for authentication (Higher is better).
encapsulates SASL authentication mechanisms.
strip: null
BOSH-Connections will have all stanzas wrapped in a body tag when passed to Strophe.Connection.xmlInput or Strophe.Connection.xmlOutput.
User overrideable function that receives XML data coming into the connection.
User overrideable function that receives XML data sent to the connection.
Checks if mechanism able to run.
Available authentication mechanisms
Close