Class: Connection

Strophe.Connection(service, options)

XMPP Connection manager

This class is the main part of Strophe. It manages a BOSH or websocket connection to an XMPP server and dispatches events to the user callbacks as data arrives.

It supports various authentication mechanisms (e.g. SASL PLAIN, SASL SCRAM), and more can be added via registerSASLMechanisms().

After creating a 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().

Constructor

new Connection(service, options)

Create and initialize a 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:

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

Parameters:
Name Type Description
service string

The BOSH or WebSocket service URL.

options ConnectionOptions

A object containing configuration options

Source:

Members

_data

Source:

_requests :Array.<Request>

Type:
Source:

_sasl_data :SASLData

Type:
Source:

addHandlers :Array.<Handler>

Type:
Source:

addTimeds :Array.<TimedHandler>

Type:
  • Array.<TimedHandler>
Source:

authcid

Authentication identity (User name)

Source:

authzid

Authorization identity

Source:

handlers :Array.<Handler>

Type:
Source:

mechanisms :Object.<string, SASLMechanism>

Type:
Source:

pass

Authentication identity (User password)

Source:

removeHandlers :Array.<Handler>

Type:
Source:

removeTimeds :Array.<TimedHandler>

Type:
  • Array.<TimedHandler>
Source:

scram_keys

The SASL SCRAM client and server keys. This variable will be populated with a non-null object of the above described form after a successful SCRAM connection

Source:

timedHandlers :Array.<TimedHandler>

Type:
  • Array.<TimedHandler>
Source:

Methods

_addSysHandler(handler, ns, name, type, id)

Private function to add a system level stanza handler.

This function is used to add a Handler for the library code. System stanza handlers are allowed to run before authentication is complete.

Parameters:
Name Type Description
handler function

The callback function.

ns string

The namespace to match.

name string

The stanza name to match.

type string

The stanza type attribute to match.

id string

The stanza id attribute to match.

Source:

_addSysTimedHandler(period, handler)

Private function to add a system level timed handler.

This function is used to add a TimedHandler for the library code. System timed handlers are allowed to run before authentication is complete.

Parameters:
Name Type Description
period number

The period of the handler.

handler function

The callback function.

Source:

(private) _attemptLegacyAuth()

Attempt legacy (i.e. non-SASL) authentication.

Source:

(private) _attemptSASLAuth(mechanisms) → {Boolean}

Iterate through an array of SASL mechanisms and attempt authentication with the highest priority (enabled) mechanism.

Parameters:
Name Type Description
mechanisms Array.<SASLMechanism>

Array of SASL mechanisms.

Source:
Returns:

mechanism_found - true or false, depending on whether a valid SASL mechanism was found with which authentication could be started.

Type
Boolean

(private) _auth2_cb(elem) → {false}

Private handler to finish legacy authentication.

This handler is called when the result from the jabber:iq:auth stanza is returned.

Parameters:
Name Type Description
elem Element

The stanza that triggered the callback.

Source:
Returns:

false to remove the handler.

Type
false

_changeConnectStatus(status, conditionopt, elemopt)

Private helper function that makes sure plugins and the user's callback are notified of connection status changes.

Parameters:
Name Type Attributes Description
status number

the new connection status, one of the values in Strophe.Status

condition string | null <optional>

the error condition

elem Element <optional>

The triggering stanza.

Source:

_connect_cb(req, _callback, rawopt)

Private handler for initial connection request.

This handler is used to process the initial connection request response from the BOSH server. It is used to set up authentication handlers and start the authentication process.

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

Parameters:
Name Type Attributes Description
req Element | Request

The current request.

_callback connectionCallback

low level (xmpp) connect callback function. Useful for plugins with their own xmpp connect callback (when they want to do something special).

raw string <optional>

The stanza as raw string.

Source:

_dataRecv(req, rawopt)

Private handler to processes incoming data from the the connection.

Except for _connect_cb handling the initial connection request, this function handles the incoming data for all requests. This function also fires stanza handlers that match each incoming stanza.

Parameters:
Name Type Attributes Description
req Element | Request

The request that has data ready.

raw string <optional>

The stanza as raw string.

Source:

_doDisconnect(conditionopt)

Private function to disconnect.

This is the last piece of the disconnection logic. This resets the connection and alerts the user's connection callback.

Parameters:
Name Type Attributes Description
condition string | null <optional>

the error condition

Source:

(private) _establishSession()

Send IQ request to establish a session with the XMPP server.

See https://xmpp.org/rfcs/rfc3921.html#session

Note: The protocol for session establishment has been determined as unnecessary and removed in RFC-6121.

Source:

_onDisconnectTimeout() → {false}

Private timeout handler for handling non-graceful disconnection.

If the graceful disconnect process does not complete within the time allotted, this handler finishes the disconnect anyway.

Source:
Returns:

false to remove the handler.

Type
false

_onIdle()

Private handler to process events during idle cycle.

This handler is called every 100ms to fire timed handlers that are ready and keep poll requests going.

Source:

(private) _onLegacyAuthIQResult() → {false}

Private handler for legacy authentication.

This handler is called in response to the initial for legacy authentication. It builds an authentication and sends it, creating a handler (calling back to _auth2_cb()) to handle the result

Source:
Returns:

false to remove the handler.

Type
false

(private) _onResourceBindResultIQ(elem) → {false}

Private handler for binding result and session start.

Parameters:
Name Type Description
elem Element

The matching stanza.

Source:
Returns:

false to remove the handler.

Type
false

(private) _onSessionResultIQ(elem) → {false}

Private handler for the server's IQ response to a client's session request.

This sets Connection.authenticated to true on success, which starts the processing of user handlers.

See https://xmpp.org/rfcs/rfc3921.html#session

Note: The protocol for session establishment has been determined as unnecessary and removed in RFC-6121.

Parameters:
Name Type Description
elem Element

The matching stanza.

Source:
Returns:

false to remove the handler.

Type
false

(private) _onStreamFeaturesAfterSASL(elem) → {false}

Parameters:
Name Type Description
elem Element

The matching stanza.

Source:
Returns:

false to remove the handler.

Type
false

(private) _queueData(element)

Queue outgoing data for later sending. Also ensures that the data is a DOMElement.

Parameters:
Name Type Description
element Element
Source:

(async, private) _sasl_challenge_cb(elem)

Private handler for the SASL challenge

Parameters:
Name Type Description
elem Element
Source:

_sasl_failure_cb(elemopt) → {false}

Private handler for SASL authentication failure.

Parameters:
Name Type Attributes Description
elem Element <optional>

The matching stanza.

Source:
Returns:

false to remove the handler.

Type
false

(private) _sasl_success_cb(elem) → {false}

Private handler for succesful SASL authentication.

Parameters:
Name Type Description
elem Element

The matching stanza.

Source:
Returns:

false to remove the handler.

Type
false

(private) _sendRestart()

Send an xmpp:restart stanza.

Source:

_sessionCachingSupported()

Checks whether sessionStorage and JSON are supported and whether we're using BOSH.

Source:

addHandler(handler, ns, name, type, idopt, fromopt, optionsopt) → {Handler}

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.

Options

With the options argument, you can specify boolean flags that affect how matches are being done.

Currently two flags exist:

  • matchBareFromJid: When set to 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 {matchBareFromJid: true} as the value of options. The default value for matchBareFromJid is false.

  • ignoreNamespaceFragment: When set to true, a fragment specified on the stanza's namespace URL will be ignored when it's matched with the one configured for the handler.

    This means that if you register like this:

    connection.addHandler( handler, 'http://jabber.org/protocol/muc', null, null, null, null, {'ignoreNamespaceFragment': true} );

    Then a stanza with XML namespace of 'http://jabber.org/protocol/muc#user' will also be matched. If 'ignoreNamespaceFragment' is false, then only stanzas with 'http://jabber.org/protocol/muc' will be matched.

Deleting the handler

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

Parameters:
Name Type Attributes Description
handler function

The user callback.

ns string

The namespace to match.

name string

The stanza name to match.

type string | Array.<string>

The stanza type (or types if an array) to match.

id string <optional>

The stanza id attribute to match.

from string <optional>

The stanza from attribute to match.

options HandlerOptions <optional>

The handler options

Source:
Returns:

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

Type
Handler

addProtocolErrorHandler(protocol, status_code, callback)

Register a handler function for when a protocol (websocker or HTTP) error occurs.

NOTE: Currently only HTTP errors for BOSH requests are handled. Patches that handle websocket errors would be very welcome.

Parameters:
Name Type Description
protocol 'HTTP' | 'websocket'

'HTTP' or 'websocket'

status_code number

Error status code (e.g 500, 400 or 404)

callback function

Function that will fire on Http error

Source:
Example
function onError(err_code){
   //do stuff
 }

 const conn = Strophe.connect('http://example.com/http-bind');
 conn.addProtocolErrorHandler('HTTP', 500, onError);
 // Triggers HTTP 500 error and onError handler will be called
 conn.connect('user_jid@incorrect_jabber_host', 'secret', onConnect);

addTimedHandler(period, handler) → {TimedHandler}

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:
Name Type Description
period number

The period of the handler.

handler function

The callback function.

Source:
Returns:

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

Type
TimedHandler

attach(jid, sidopt, ridopt, callbackopt, waitopt, holdopt, windopt)

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:
Name Type Attributes Description
jid string | function

The full JID that is bound by the session.

sid string <optional>

The SID of the BOSH session.

rid number <optional>

The current RID of the BOSH session. This RID will be used by the next request.

callback function <optional>

The connect callback function.

wait number <optional>

The 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.

hold number <optional>

The 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).

wind number <optional>

The optional HTTBIND window value. This is the allowed range of request ids that are valid. The default is 5.

Source:

authenticate(matched)

Set up authentication

Continues the initial connection request by setting up authentication handlers and starting the authentication process.

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

Parameters:
Name Type Description
matched Array.<SASLMechanism>

Array of SASL mechanisms supported.

Source:

bind()

Sends an IQ to the XMPP server to bind a JID resource for this session.

https://tools.ietf.org/html/rfc6120#section-7.5

If explicitResourceBinding was set to a truthy value in the options passed to the Connection constructor, then this function needs to be called explicitly by the client author.

Otherwise it'll be called automatically as soon as the XMPP server advertises the "urn:ietf:params:xml:ns:xmpp-bind" stream feature.

Source:

connect(jid, pass, callback, waitopt, holdopt, routeopt, authcidopt, disconnection_timeoutopt)

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:
Name Type Attributes Default Description
jid string

The user's JID. This may be a bare JID, or a full JID. If a node is not supplied, SASL OAUTHBEARER or SASL ANONYMOUS authentication will be attempted (OAUTHBEARER will process the provided password value as an access token). (String or Object) pass - The user's password, or an object containing the users SCRAM client and server keys, in a fashion described as follows:

{ name: String, representing the hash used (eg. SHA-1),
  salt: String, base64 encoded salt used to derive the client key,
  iter: Int,    the iteration count used to derive the client key,
  ck:   String, the base64 encoding of the SCRAM client key
  sk:   String, the base64 encoding of the SCRAM server key
}
pass string | Password

The user password

callback function

The connect callback function.

wait number <optional>

The 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.

hold number <optional>

The 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).

route string <optional>

The optional route value.

authcid string <optional>

The optional alternative authentication identity (username) if intending to impersonate another user. When using the SASL-EXTERNAL authentication mechanism, for example with client certificates, then the authcid value is used to determine whether an authorization JID (authzid) should be sent to the server. The authzid should NOT be sent to the server if the authzid and authcid are the same. So to prevent it from being sent (for example when the JID is already contained in the client certificate), set authcid to that same JID. See XEP-178 for more details.

disconnection_timeout number <optional>
3000

The optional disconnection timeout in milliseconds before _doDisconnect will be called.

Source:

deleteHandler(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:
Name Type Description
handRef Handler

The handler reference.

Source:

deleteTimedHandler(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:
Name Type Description
handRef TimedHandler

The handler reference.

Source:

disconnect(reasonopt)

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. If the Connection object isn't connected, at least tries to abort all pending requests so the connection object won't generate successful requests (which were already opened).

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

Parameters:
Name Type Attributes Description
reason string <optional>

The reason the disconnect is occuring.

Source:

flush()

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.

Source:

getUniqueId(suffix) → {string}

Generate a unique ID for use in elements.

All 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:
Name Type Description
suffix string

A optional suffix to append to the id.

Source:
Returns:

A unique string to be used for the id attribute.

Type
string

nextValidRid(rid)

User overrideable function that receives the new valid rid.

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

Connection.nextValidRid = function (rid) { (user code) };

Parameters:
Name Type Description
rid number

The next valid rid

Source:

pause()

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.

Source:

rawInput(data)

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

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

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

Parameters:
Name Type Description
data string

The data received by the connection.

Source:

rawOutput(data)

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

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

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

Parameters:
Name Type Description
data string

The data sent by the connection.

Source:

registerSASLMechanism(Mechanism)

Register a single SASL mechanism, to be supported by this client.

Parameters:
Name Type Description
Mechanism any

Object with a Strophe.SASLMechanism prototype

Source:

registerSASLMechanisms(mechanisms)

Register the SASL mechanisms which will be supported by this instance of Connection (i.e. which this XMPP client will support).

Parameters:
Name Type Description
mechanisms Array.<SASLMechanism>

Array of objects with SASLMechanism prototypes

Source:

reset()

Reset the connection.

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

Source:

restore(jid, callback, waitopt, holdopt, windopt)

Attempt to restore a cached BOSH session.

This function is only useful in conjunction with providing the "keepalive":true option when instantiating a new Connection.

When "keepalive" is set to true, Strophe will cache the BOSH tokens RID (Request ID) and SID (Session ID) and then when this function is called, it will attempt to restore the session from those cached tokens.

This function must therefore be called instead of connect or attach.

For an example on how to use it, please see examples/restore.js

Parameters:
Name Type Attributes Description
jid string

The user's JID. This may be a bare JID or a full JID.

callback function

The connect callback function.

wait number <optional>

The 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.

hold number <optional>

The 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).

wind number <optional>

The optional HTTBIND window value. This is the allowed range of request ids that are valid. The default is 5.

Source:

resume()

Resume the request manager.

This resumes after pause() has been called.

Source:

send(stanza)

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:
Name Type Description
stanza Element | Builder | Array.<Element> | Array.<Builder>

The stanza to send

Source:

sendIQ(stanza, callbackopt, errbackopt, timeoutopt) → {string}

Helper function to send IQ stanzas.

Parameters:
Name Type Attributes Description
stanza Element | Builder

The stanza to send.

callback function <optional>

The callback function for a successful request.

errback function <optional>

The callback function for a failed or timed out request. On timeout, the stanza will be null.

timeout number <optional>

The time specified in milliseconds for a timeout to occur.

Source:
Returns:

The id used to send the IQ.

Type
string

sendPresence(stanza, callbackopt, errbackopt, timeoutopt) → {string}

Helper function to send presence stanzas. The main benefit is for sending presence stanzas for which you expect a responding presence stanza with the same id (for example when leaving a chat room).

Parameters:
Name Type Attributes Description
stanza Element

The stanza to send.

callback function <optional>

The callback function for a successful request.

errback function <optional>

The callback function for a failed or timed out request. On timeout, the stanza will be null.

timeout number <optional>

The time specified in milliseconds for a timeout to occur.

Source:
Returns:

The id used to send the presence.

Type
string

setProtocol()

Select protocal based on this.options or this.service

Source:

sortMechanismsByPriority(mechanisms)

Sorts an array of objects with prototype SASLMechanism according to their priorities.

Parameters:
Name Type Description
mechanisms Array.<SASLMechanism>

Array of SASL mechanisms.

Source:

xmlInput(elem)

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

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

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

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

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

Parameters:
Name Type Description
elem Node | MessageEvent

The XML data received by the connection.

Source:

xmlOutput(elem)

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

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

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

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

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

Parameters:
Name Type Description
elem Element

The XMLdata sent by the connection.

Source:

(static) addConnectionPlugin(name, ptype)

Extends the Connection object with the given plugin.

Parameters:
Name Type Description
name string

The name of the extension.

ptype Object

The plugin's prototype.

Source: