Converse converse.js

Class: Connection

Connection()

The Connection class manages the connection to the XMPP server. It's agnostic concerning the underlying protocol (i.e. websocket, long-polling via BOSH or websocket inside a shared worker).

Constructor

new Connection()

Source:

Classes

Connection

Members

authcid

Variable: authcid Authentication identity (User name).

Source:

authzid

Variable: authzid Authorization identity.

Source:

pass

Variable: pass Authentication identity (User password).

Source:

scram_keys

Variable: 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:

Methods

_addSysHandler()

PrivateFunction: _addSysHandler 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: (Function) handler - The callback function. (String) ns - The namespace to match. (String) name - The stanza name to match. (String) type - The stanza type attribute to match. (String) id - The stanza id attribute to match.

Source:

_addSysTimedHandler()

PrivateFunction: _addSysTimedHandler Private function to add a system level timed handler.

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

Parameters: (Integer) period - The period of the handler. (Function) handler - The callback function.

Source:

_attemptLegacyAuth()

PrivateFunction: _attemptLegacyAuth

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

Source:

_attemptSASLAuth()

PrivateFunction: _attemptSASLAuth

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

Parameters: (Array) mechanisms - Array of SASL mechanisms.

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

Source:

_auth2_cb()

PrivateFunction: _auth2_cb Private handler to finish legacy authentication.

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

Parameters: (XMLElement) elem - The stanza that triggered the callback.

Returns: false to remove the handler.

Source:

_changeConnectStatus()

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

Parameters: (Integer) status - the new connection status, one of the values in Strophe.Status (String) condition - the error condition or null (XMLElement) elem - The triggering stanza.

Source:

_connect_cb()

PrivateFunction: _connect_cb 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: (Strophe.Request) req - The current request. (Function) _callback - low level (xmpp) connect callback function. Useful for plugins with their own xmpp connect callback (when they want to do something special).

Source:

_dataRecv()

PrivateFunction: _dataRecv 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: (Strophe.Request) req - The request that has data ready. (string) req - The stanza a raw string (optiona).

Source:

_doDisconnect()

PrivateFunction: _doDisconnect Private function to disconnect.

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

Source:

_establishSession()

PrivateFunction: _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()

PrivateFunction: _onDisconnectTimeout 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.

Returns: false to remove the handler.

Source:

_onIdle()

PrivateFunction: _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:

_onLegacyAuthIQResult()

PrivateFunction: _onLegacyAuthIQResult 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

Parameters: (XMLElement) elem - The stanza that triggered the callback.

Returns: false to remove the handler.

Source:

_onResourceBindResultIQ()

PrivateFunction: _onResourceBindIQ Private handler for binding result and session start.

Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_onSessionResultIQ()

PrivateFunction: _onSessionResultIQ 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: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_onStreamFeaturesAfterSASL()

PrivateFunction: _onStreamFeaturesAfterSASL Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_queueData()

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

Source:

(async) _sasl_challenge_cb()

PrivateFunction: _sasl_challenge_cb Private handler for the SASL challenge

Source:

_sasl_failure_cb()

PrivateFunction: _sasl_failure_cb Private handler for SASL authentication failure.

Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_sasl_success_cb()

PrivateFunction: _sasl_success_cb Private handler for succesful SASL authentication.

Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_sendRestart()

PrivateFunction: _sendRestart Send an xmpp:restart stanza.

Source:

_sessionCachingSupported()

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

Source:

addHandler()

Function: addHandler 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: (Function) handler - The user callback. (String) ns - The namespace to match. (String) name - The stanza name to match. (String|Array) type - The stanza type (or types if an array) to match. (String) id - The stanza id attribute to match. (String) from - The stanza from attribute to match. (String) options - The handler options

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

Source:

addProtocolErrorHandler()

Function: addProtocolErrorHandler 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: (String) protocol - 'HTTP' or 'websocket' (Integer) status_code - Error status code (e.g 500, 400 or 404) (Function) callback - Function that will fire on Http error

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

let 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);

Source:

addTimedHandler()

Function: addTimedHandler 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) period - The period of the handler. (Function) handler - The callback function.

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

Source:

attach()

Function: attach 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) jid - The full JID that is bound by the session. (String) sid - The SID of the BOSH session. (String) rid - The current RID of the BOSH session. This RID will be used by the next request. (Function) callback The connect callback function. (Integer) wait - 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. (Integer) hold - 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). (Integer) wind - The optional HTTBIND window value. This is the allowed range of request ids that are valid. The default is 5.

Source:

authenticate()

Function: authenticate 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: (Array) matched - Array of SASL mechanisms supported.

Source:

bind()

Function: 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 Strophe.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()

Function: connect 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) jid - 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
 }

(Function) callback - The connect callback function. (Integer) wait - 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. (Integer) hold - 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). (String) route - The optional route value. (String) authcid - 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. (Integer) disconnection_timeout - The optional disconnection timeout in milliseconds before _doDisconnect will be called.

Source:

deleteHandler()

Function: deleteHandler 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: (Handler) handRef - The handler reference.

Source:

deleteTimedHandler()

Function: deleteTimedHandler 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) handRef - The handler reference.

Source:

disconnect()

Function: disconnect 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: (String) reason - The reason the disconnect is occuring.

Source:

flush()

Function: 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()

Function: getUniqueId 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: (String) suffix - A optional suffix to append to the id.

Returns: A unique string to be used for the id attribute.

Source:

nextValidRid()

Function: nextValidRid User overrideable function that receives the new valid rid.

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

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

Parameters: (Number) rid - The next valid rid

Source:

onConnectStatusChanged(status, message)

Callback method called by Strophe as the Connection goes through various states while establishing or tearing down a connection.

Parameters:
Name Type Description
status Number
message String
Source:

pause()

Function: 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()

Function: 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) data - The data received by the connection.

Source:

rawOutput()

Function: 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) data - The data sent by the connection.

Source:

registerSASLMechanism()

Function: registerSASLMechanism

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

Parameters: (Object) mechanism - Object with a Strophe.SASLMechanism prototype

Source:

registerSASLMechanisms()

Function: registerSASLMechanisms

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

Parameters: (Array) mechanisms - Array of objects with Strophe.SASLMechanism prototypes

Source:

reset()

Function: reset Reset the connection.

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

Source:

restore()

Function: restore Attempt to restore a cached BOSH session.

This function is only useful in conjunction with providing the "keepalive":true option when instantiating a new Strophe.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: (String) jid - The user's JID. This may be a bare JID or a full JID. (Function) callback - The connect callback function. (Integer) wait - 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. (Integer) hold - 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). (Integer) wind - The optional HTTBIND window value. This is the allowed range of request ids that are valid. The default is 5.

Source:

resume()

Function: resume Resume the request manager.

This resumes after pause() has been called.

Source:

send()

Function: send 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.

Source:

sendIQ()

Function: sendIQ Helper function to send IQ stanzas.

Parameters: (XMLElement) elem - The stanza to send. (Function) callback - The callback function for a successful request. (Function) errback - The callback function for a failed or timed out request. On timeout, the stanza will be null. (Integer) timeout - The time specified in milliseconds for a timeout to occur.

Returns: The id used to send the IQ.

Source:

sendPresence()

Function: sendPresence 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: (XMLElement) elem - The stanza to send. (Function) callback - The callback function for a successful request. (Function) errback - The callback function for a failed or timed out request. On timeout, the stanza will be null. (Integer) timeout - The time specified in milliseconds for a timeout to occur.

Returns: The id used to send the presence.

Source:

setProtocol()

Function: setProtocol Select protocal based on this.options or this.service

Source:

sortMechanismsByPriority()

Function: sortMechanismsByPriority

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

Parameters: (Array) mechanisms - Array of SASL mechanisms.

Source:

(async) switchTransport()

Switch to a different transport if a service URL is available for it.

When reconnecting with a new transport, we call setUserJID so that a new resource is generated, to avoid multiple server-side sessions with the same resource.

We also call _proto._doDisconnect so that connection event handlers for the old transport are removed.

Source:

xmlInput()

Function: 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 tag for WebSocket-Connoctions will be passed as selfclosing here.

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

Parameters: (XMLElement) elem - The XML data received by the connection.

Source:

xmlOutput()

Function: 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 tag for WebSocket-Connoctions will be passed as selfclosing here.

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

Parameters: (XMLElement) elem - The XMLdata sent by the connection.

Source:

(static) onConnected(reconnecting)

Called as soon as a new connection has been established, either by logging in or by attaching to an existing BOSH session.

Parameters:
Name Type Description
reconnecting Boolean

Whether Converse.js reconnected from an earlier dropped session.

Source:

(static) onConnected(reconnecting)

Called as soon as a new connection has been established, either by logging in or by attaching to an existing BOSH session.

Parameters:
Name Type Description
reconnecting Boolean

Whether Converse.js reconnected from an earlier dropped session.

Source:

(static) setDisconnectionCause(cause, reasonopt, overrideopt)

Used to keep track of why we got disconnected, so that we can decide on what the next appropriate action is (in onDisconnected)

Parameters:
Name Type Attributes Description
cause Number

The status number as received from Strophe.

reason String <optional>

An optional user-facing message as to why there was a disconnection.

override Boolean <optional>

An optional flag to replace any previous disconnection cause and reason.

Source:

(static) setDisconnectionCause(cause, reasonopt, overrideopt)

Used to keep track of why we got disconnected, so that we can decide on what the next appropriate action is (in onDisconnected)

Parameters:
Name Type Attributes Description
cause Number

The status number as received from Strophe.

reason String <optional>

An optional user-facing message as to why there was a disconnection.

override Boolean <optional>

An optional flag to replace any previous disconnection cause and reason.

Source:

Connection()

Constructor: Strophe.Connection 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.

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

Options common to both Websocket and BOSH:

cookies:

The cookies option allows you to pass in cookies to be added to the document. These cookies will then be included in the BOSH XMLHttpRequest or in the websocket connection.

The passed in value must be a map of cookie names and string values.

{ "myCookie": { "value": "1234", "domain": ".example.org", "path": "/", "expires": expirationDate } }

Note that cookies can't be set in this way for other domains (i.e. cross-domain). Those cookies need to be set under those domains, for example they can be set server-side by making a XHR call to that domain to ask it to set any necessary cookies.

mechanisms:

The mechanisms option allows you to specify the SASL mechanisms that this instance of Strophe.Connection (and therefore your XMPP client) will support.

The value must be an array of objects with Strophe.SASLMechanism prototypes.

If nothing is specified, then the following mechanisms (and their priorities) are registered:

 SCRAM-SHA-512 - 72
 SCRAM-SHA-384 - 71
 SCRAM-SHA-256 - 70
 SCRAM-SHA-1   - 60
 PLAIN         - 50
 OAUTHBEARER   - 40
 X-OAUTH2      - 30
 ANONYMOUS     - 20
 EXTERNAL      - 10

explicitResourceBinding:

If explicitResourceBinding is set to a truthy value, then the XMPP client needs to explicitly call Strophe.Connection.prototype.bind once the XMPP server has advertised the "urn:ietf:params:xml:ns:xmpp-bind" feature.

Making this step explicit allows client authors to first finish other stream related tasks, such as setting up an XEP-0198 Stream Management session, before binding the JID resource for this session.

WebSocket options:

protocol:

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

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

worker:

Set this option to URL from where the shared worker script should be loaded.

To run the websocket connection inside a shared worker. This allows you to share a single websocket-based connection between multiple Strophe.Connection instances, for example one per browser tab.

The script to use is the one in src/shared-connection-worker.js.

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.

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

You can also toggle this on an already established connection.

conn.options.sync = true;

The customHeaders option can be used to provide custom HTTP headers to be included in the XMLHttpRequests made.

The keepalive option can be used to instruct Strophe to maintain the current BOSH session across interruptions such as webpage reloads.

It will do this by caching the sessions tokens in sessionStorage, and when "restore" is called it will check whether there are cached tokens with which it can resume an existing session.

The withCredentials option should receive a Boolean value and is used to indicate wether cookies should be included in ajax requests (by default they're not). Set this value to true if you are connecting to a BOSH service and for some reason need to send cookies to it. In order for this to work cross-domain, the server must also enable credentials by setting the Access-Control-Allow-Credentials response header to "true". For most usecases however this setting should be false (which is the default). Additionally, when using Access-Control-Allow-Credentials, the Access-Control-Allow-Origin header can't be set to the wildcard "*", but instead must be restricted to actual domains.

The contentType option can be set to change the default Content-Type of "text/xml; charset=utf-8", which can be useful to reduce the amount of CORS preflight requests that are sent to the server.

Parameters: (String) service - The BOSH or WebSocket service URL. (Object) options - A hash of configuration options

Returns: A new Strophe.Connection object.

Constructor

new Connection()

Source:

Classes

Connection

Members

authcid

Variable: authcid Authentication identity (User name).

Source:

authzid

Variable: authzid Authorization identity.

Source:

pass

Variable: pass Authentication identity (User password).

Source:

scram_keys

Variable: 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:

Methods

_addSysHandler()

PrivateFunction: _addSysHandler 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: (Function) handler - The callback function. (String) ns - The namespace to match. (String) name - The stanza name to match. (String) type - The stanza type attribute to match. (String) id - The stanza id attribute to match.

Source:

_addSysTimedHandler()

PrivateFunction: _addSysTimedHandler Private function to add a system level timed handler.

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

Parameters: (Integer) period - The period of the handler. (Function) handler - The callback function.

Source:

_attemptLegacyAuth()

PrivateFunction: _attemptLegacyAuth

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

Source:

_attemptSASLAuth()

PrivateFunction: _attemptSASLAuth

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

Parameters: (Array) mechanisms - Array of SASL mechanisms.

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

Source:

_auth2_cb()

PrivateFunction: _auth2_cb Private handler to finish legacy authentication.

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

Parameters: (XMLElement) elem - The stanza that triggered the callback.

Returns: false to remove the handler.

Source:

_changeConnectStatus()

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

Parameters: (Integer) status - the new connection status, one of the values in Strophe.Status (String) condition - the error condition or null (XMLElement) elem - The triggering stanza.

Source:

_connect_cb()

PrivateFunction: _connect_cb 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: (Strophe.Request) req - The current request. (Function) _callback - low level (xmpp) connect callback function. Useful for plugins with their own xmpp connect callback (when they want to do something special).

Source:

_dataRecv()

PrivateFunction: _dataRecv 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: (Strophe.Request) req - The request that has data ready. (string) req - The stanza a raw string (optiona).

Source:

_doDisconnect()

PrivateFunction: _doDisconnect Private function to disconnect.

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

Source:

_establishSession()

PrivateFunction: _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()

PrivateFunction: _onDisconnectTimeout 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.

Returns: false to remove the handler.

Source:

_onIdle()

PrivateFunction: _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:

_onLegacyAuthIQResult()

PrivateFunction: _onLegacyAuthIQResult 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

Parameters: (XMLElement) elem - The stanza that triggered the callback.

Returns: false to remove the handler.

Source:

_onResourceBindResultIQ()

PrivateFunction: _onResourceBindIQ Private handler for binding result and session start.

Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_onSessionResultIQ()

PrivateFunction: _onSessionResultIQ 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: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_onStreamFeaturesAfterSASL()

PrivateFunction: _onStreamFeaturesAfterSASL Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_queueData()

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

Source:

(async) _sasl_challenge_cb()

PrivateFunction: _sasl_challenge_cb Private handler for the SASL challenge

Source:

_sasl_failure_cb()

PrivateFunction: _sasl_failure_cb Private handler for SASL authentication failure.

Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_sasl_success_cb()

PrivateFunction: _sasl_success_cb Private handler for succesful SASL authentication.

Parameters: (XMLElement) elem - The matching stanza.

Returns: false to remove the handler.

Source:

_sendRestart()

PrivateFunction: _sendRestart Send an xmpp:restart stanza.

Source:

_sessionCachingSupported()

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

Source:

addHandler()

Function: addHandler 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: (Function) handler - The user callback. (String) ns - The namespace to match. (String) name - The stanza name to match. (String|Array) type - The stanza type (or types if an array) to match. (String) id - The stanza id attribute to match. (String) from - The stanza from attribute to match. (String) options - The handler options

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

Source:

addProtocolErrorHandler()

Function: addProtocolErrorHandler 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: (String) protocol - 'HTTP' or 'websocket' (Integer) status_code - Error status code (e.g 500, 400 or 404) (Function) callback - Function that will fire on Http error

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

let 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);

Source:

addTimedHandler()

Function: addTimedHandler 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) period - The period of the handler. (Function) handler - The callback function.

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

Source:

attach()

Function: attach 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) jid - The full JID that is bound by the session. (String) sid - The SID of the BOSH session. (String) rid - The current RID of the BOSH session. This RID will be used by the next request. (Function) callback The connect callback function. (Integer) wait - 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. (Integer) hold - 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). (Integer) wind - The optional HTTBIND window value. This is the allowed range of request ids that are valid. The default is 5.

Source:

authenticate()

Function: authenticate 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: (Array) matched - Array of SASL mechanisms supported.

Source:

bind()

Function: 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 Strophe.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()

Function: connect 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) jid - 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
 }

(Function) callback - The connect callback function. (Integer) wait - 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. (Integer) hold - 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). (String) route - The optional route value. (String) authcid - 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. (Integer) disconnection_timeout - The optional disconnection timeout in milliseconds before _doDisconnect will be called.

Source:

deleteHandler()

Function: deleteHandler 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: (Handler) handRef - The handler reference.

Source:

deleteTimedHandler()

Function: deleteTimedHandler 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) handRef - The handler reference.

Source:

disconnect()

Function: disconnect 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: (String) reason - The reason the disconnect is occuring.

Source:

flush()

Function: 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()

Function: getUniqueId 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: (String) suffix - A optional suffix to append to the id.

Returns: A unique string to be used for the id attribute.

Source:

nextValidRid()

Function: nextValidRid User overrideable function that receives the new valid rid.

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

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

Parameters: (Number) rid - The next valid rid

Source:

onConnectStatusChanged(status, message)

Callback method called by Strophe as the Connection goes through various states while establishing or tearing down a connection.

Parameters:
Name Type Description
status Number
message String
Source:

pause()

Function: 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()

Function: 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) data - The data received by the connection.

Source:

rawOutput()

Function: 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) data - The data sent by the connection.

Source:

registerSASLMechanism()

Function: registerSASLMechanism

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

Parameters: (Object) mechanism - Object with a Strophe.SASLMechanism prototype

Source:

registerSASLMechanisms()

Function: registerSASLMechanisms

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

Parameters: (Array) mechanisms - Array of objects with Strophe.SASLMechanism prototypes

Source:

reset()

Function: reset Reset the connection.

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

Source:

restore()

Function: restore Attempt to restore a cached BOSH session.

This function is only useful in conjunction with providing the "keepalive":true option when instantiating a new Strophe.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: (String) jid - The user's JID. This may be a bare JID or a full JID. (Function) callback - The connect callback function. (Integer) wait - 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. (Integer) hold - 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). (Integer) wind - The optional HTTBIND window value. This is the allowed range of request ids that are valid. The default is 5.

Source:

resume()

Function: resume Resume the request manager.

This resumes after pause() has been called.

Source:

send()

Function: send 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.

Source:

sendIQ()

Function: sendIQ Helper function to send IQ stanzas.

Parameters: (XMLElement) elem - The stanza to send. (Function) callback - The callback function for a successful request. (Function) errback - The callback function for a failed or timed out request. On timeout, the stanza will be null. (Integer) timeout - The time specified in milliseconds for a timeout to occur.

Returns: The id used to send the IQ.

Source:

sendPresence()

Function: sendPresence 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: (XMLElement) elem - The stanza to send. (Function) callback - The callback function for a successful request. (Function) errback - The callback function for a failed or timed out request. On timeout, the stanza will be null. (Integer) timeout - The time specified in milliseconds for a timeout to occur.

Returns: The id used to send the presence.

Source:

setProtocol()

Function: setProtocol Select protocal based on this.options or this.service

Source:

sortMechanismsByPriority()

Function: sortMechanismsByPriority

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

Parameters: (Array) mechanisms - Array of SASL mechanisms.

Source:

(async) switchTransport()

Switch to a different transport if a service URL is available for it.

When reconnecting with a new transport, we call setUserJID so that a new resource is generated, to avoid multiple server-side sessions with the same resource.

We also call _proto._doDisconnect so that connection event handlers for the old transport are removed.

Source:

xmlInput()

Function: 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 tag for WebSocket-Connoctions will be passed as selfclosing here.

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

Parameters: (XMLElement) elem - The XML data received by the connection.

Source:

xmlOutput()

Function: 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 tag for WebSocket-Connoctions will be passed as selfclosing here.

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

Parameters: (XMLElement) elem - The XMLdata sent by the connection.

Source:

(static) onConnected(reconnecting)

Called as soon as a new connection has been established, either by logging in or by attaching to an existing BOSH session.

Parameters:
Name Type Description
reconnecting Boolean

Whether Converse.js reconnected from an earlier dropped session.

Source:

(static) onConnected(reconnecting)

Called as soon as a new connection has been established, either by logging in or by attaching to an existing BOSH session.

Parameters:
Name Type Description
reconnecting Boolean

Whether Converse.js reconnected from an earlier dropped session.

Source:

(static) setDisconnectionCause(cause, reasonopt, overrideopt)

Used to keep track of why we got disconnected, so that we can decide on what the next appropriate action is (in onDisconnected)

Parameters:
Name Type Attributes Description
cause Number

The status number as received from Strophe.

reason String <optional>

An optional user-facing message as to why there was a disconnection.

override Boolean <optional>

An optional flag to replace any previous disconnection cause and reason.

Source:

(static) setDisconnectionCause(cause, reasonopt, overrideopt)

Used to keep track of why we got disconnected, so that we can decide on what the next appropriate action is (in onDisconnected)

Parameters:
Name Type Attributes Description
cause Number

The status number as received from Strophe.

reason String <optional>

An optional user-facing message as to why there was a disconnection.

override Boolean <optional>

An optional flag to replace any previous disconnection cause and reason.

Source: