Strophe.js
    Preparing search index...

    Class default

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

    Strophe

    Index
    • 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

      • service: string

        The BOSH or WebSocket service URL.

      • options: ConnectionOptions = {}

        A object containing configuration options

      Returns default

    _data: (Element | "restart")[]
    _disconnectTimeout: default
    _idleTimeout: Timeout
    _proto: Transport
    _requests: Request[]
    _sasl_challenge_handler: default
    _sasl_data: SASLData
    _sasl_failure_handler: default
    _sasl_mechanism: default
    _sasl_success_handler: default
    _smHandlers: default[]
    _uniqueId: number
    addHandlers: default[]
    addTimeds: default[]
    authcid: string
    authenticated: boolean
    authzid: string
    connect_callback: ConnectCallback
    connected: boolean
    disconnecting: boolean
    disconnection_timeout: number
    do_authentication: boolean
    do_bind: boolean
    do_session: boolean
    domain: string
    features: Element
    handlers: default[]
    iqFallbackHandler: default
    jid: string
    maxRetries: number
    mechanisms: Record<string, default>
    pass: string | Password
    paused: boolean
    protocolErrorHandlers: ProtocolErrorHandlers
    removeHandlers: default[]
    removeTimeds: default[]
    restored: boolean
    role?: "primary" | "secondary"

    This connection's role in a shared-worker setup: the 'primary' tab drives the stream, 'secondary' tabs share it. undefined outside worker mode. Assigned by the worker (see Connection#onRoleChanged).

    scram_keys: Record<string, unknown>
    service: string

    The XEP-0198 Stream Management engine. Only present when the enableStreamManagement option is set on a websocket connection. Under the worker option this is a StreamManagementMirror: the engine itself lives inside the shared worker and the mirror only reflects the session state. Typed against the shared StreamManagementController interface so the two are interchangeable here.

    timedHandlers: default[]
    • 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

      • handler: (stanza: Element) => boolean

        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.

      Returns default

    • 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

      • period: number

        The period of the handler.

      • handler: () => boolean

        The callback function.

      Returns default

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

      Parameters

      • status: number

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

      • Optionalcondition: string

        the error condition

      • Optionalelem: Element

        The triggering stanza.

      Returns void

    • 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

      • req: Element | Request

        The current request.

      • Optional_callback: ConnectCallback

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

      • Optionalraw: string

        The stanza as raw string.

      Returns void

    • 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

      • req: Element | Request

        The request that has data ready.

      • Optionalraw: string

        The stanza as raw string.

      Returns void

    • 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

      • Optionalcondition: string

        the error condition

      Returns void

    • 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 boolean

      false to remove the handler.

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

      Returns void

    • Called at the CONNECTED-emission points of the connect flow, just before CONNECTED is emitted i.e. once the full JID is final (resource bound, legacy session established, or legacy auth completed).

      Under the worker option the bound JID is always reported to the shared worker — with or without Stream Management — so it can hand the right JID to attaching tabs, release joins parked on the handshake, and (when this stream's features advertised SM) start a fresh SM session itself (it answers with _smEnabled, which updates the mirror).

      Otherwise, if the server supports XEP-0198 and nothing was resumed, a fresh SM session is started from here. The XEP allows any time after binding.

      Returns void

    • Private handler for a successful XEP-0198 stream resumption.

      The engine reconciles the server's 'h' and re-sends whatever the server didn't acknowledge.

      The connection state is restored, this.jid is set back to the JID that was bound when the SM session was established, before CONNECTED is emitted, so no stanza can ever be stamped with a resource the server doesn't know.

      Parameters

      • elem: Element

        The nonza.

      Returns boolean

      true to keep the handler.

    • Private handler for a failed or .

      The engine resets its state; after a failed resumption it also salvages the unacked queue (re-sent once a fresh session reaches ), and the connection falls back to binding a resource on this same stream, per XEP-0198 ("the server SHOULD allow the client to bind a resource at this point"). A refused needs neither: the stream is alive and bound, it just runs without SM.

      Parameters

      • elem: Element

        The nonza.

      Returns boolean

      true to keep the handler.

    • Continue the connect flow with resource binding, once it is clear no XEP-0198 resumption will happen (no SM support, no resumable state, a failed , or the shared worker reporting _smNoState).

      Returns void

    • Register the XEP-0198 nonza handlers (idempotently) They are system handlers, so they run before authentication completes, which the resume flow requires.

      Returns void

    • Private handler for SASL authentication failure.

      Parameters

      • elem: Element

        The matching stanza.

      Returns boolean

      false to remove the handler.

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

      Returns boolean

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

      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.

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

      Parameters

      • handler: (stanza: Element) => boolean

        The user callback.

      • ns: string

        The namespace to match.

      • name: string

        The stanza name to match.

      • type: string | string[]

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

      • Optionalid: string

        The stanza id attribute to match.

      • Optionalfrom: string

        The stanza from attribute to match.

      • Optionaloptions: HandlerOptions

        The handler options

      Returns default

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

    • 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

      • 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

      Returns void

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

      • period: number

        The period of the handler.

      • handler: () => boolean

        The callback function.

      Returns default

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

    • 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

      • jid: string | ConnectCallback

        The full JID that is bound by the session.

      • Optionalsid: string

        The SID of the BOSH session.

      • Optionalrid: number

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

      • Optionalcallback: ConnectCallback

        The connect callback function.

      • Optionalwait: number

        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.

      • Optionalhold: number

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

      • Optionalwind: number

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

      Returns void

    • 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

      • matched: default[]

        Array of SASL mechanisms supported.

      Returns void

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

      Returns void

    • 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

      • 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

      • Optionalcallback: ConnectCallback

        The connect callback function.

      • Optionalwait: number

        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.

      • Optionalhold: number

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

      • Optionalroute: string

        The optional route value.

      • Optionalauthcid: string

        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 = 3000

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

      Returns void

    • 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

      • handRef: default

        The handler reference.

      Returns void

    • 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

      • handRef: default

        The handler reference.

      Returns void

    • 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

      • Optionalreason: string

        The reason the disconnect is occuring.

      Returns void

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

      Returns void

    • 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

      • Optionalsuffix: string | number

        A optional suffix to append to the id.

      Returns string

      A unique string to be used for the id attribute.

    • Returns boolean

      true if the current session was established by resuming a previous one via XEP-0198 Stream Management (in which case the previously bound resource is still valid and roster/presence state was retained by the server).

    • Returns boolean

      true if a XEP-0198 Stream Management session is currently active (i.e. was received or a session was resumed).

    • User overrideable function that receives the new valid rid.

      Parameters

      • _rid: number

        The next valid rid

      Returns void

    • User overrideable function that receives message and presence stanzas sent by another tab sharing this connection (via the worker option), so every tab can render what any tab sent.

      Deliberately separate from the inbound handler pipeline: these stanzas were sent, not received, so they must not trigger stanza handlers. IQs are not reflected — they are request/response traffic private to the sending tab.

      Parameters

      • _elem: Element

        The sent stanza.

      Returns void

    • User overrideable function that receives the new role of this connection in a shared-worker setup.

      Called when the shared worker assigns or changes this tab's role, for example when this tab is promoted to 'primary' after the previous primary tab went away.

      Parameters

      • _role: "primary" | "secondary"

        The new role ('primary' or 'secondary')

      Returns void

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

      Returns void

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

      Parameters

      • _data: string

        The data received by the connection.

      Returns void

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

      Parameters

      • _data: string

        The data sent by the connection.

      Returns void

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

      Parameters

      • Mechanism: any

        Object with a Strophe.SASLMechanism prototype

      Returns void

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

      Parameters

      • Optionalmechanisms: (new (...args: any[]) => default)[]

        Array of objects with SASLMechanism prototypes

      Returns void

    • Reset the connection.

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

      Returns void

    • 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

      • Optionaljid: string

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

      • Optionalcallback: ConnectCallback

        The connect callback function.

      • Optionalwait: number

        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.

      • Optionalhold: number

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

      • Optionalwind: number

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

      Returns void

    • Resume the request manager.

      This resumes after pause() has been called.

      Returns void

    • 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

      • stanza: Element | Builder | (Element | Builder)[]

        The stanza to send

      Returns void

    • Helper function to send IQ stanzas.

      Parameters

      • stanza: Element | Builder

        The stanza to send.

      • Optionalcallback: (stanza: Element) => void

        The callback function for a successful request.

      • Optionalerrback: (stanza: Element) => void

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

      • Optionaltimeout: number

        The time specified in milliseconds for a timeout to occur.

      Returns string

      The id used to send the IQ.

    • 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

      • stanza: Element | Builder

        The stanza to send.

      • Optionalcallback: (stanza: Element) => void

        The callback function for a successful request.

      • Optionalerrback: (stanza: Element) => void

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

      • Optionaltimeout: number

        The time specified in milliseconds for a timeout to occur.

      Returns string

      The id used to send the presence.

    • Select protocal based on this.options or this.service

      Returns void

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

      Parameters

      • mechanisms: default[]

        Array of SASL mechanisms.

      Returns default[]

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

      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

      • _elem: Node | MessageEvent<any>

        The XML data received by the connection.

      Returns void

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

      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

      • _elem: Element

        The XMLdata sent by the connection.

      Returns void

    • Extends the Connection object with the given plugin.

      Parameters

      • name: string

        The name of the extension.

      • ptype: object

        The plugin's prototype.

      Returns void

    • Register an optional transport, selectable via the protocol connection option. Used to plug in environment-specific transports (such as the Node-only XEP-0114 component transport) without the core browser build depending on them.

      Parameters

      • name: string

        The protocol option value that selects this transport.

      • manager: new (connection: default) => Transport

        The transport (protocol-manager) constructor.

      Returns void