Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/strophe/strophejs/llms.txt

Use this file to discover all available pages before exploring further.

Strophe.js exposes a collection of utility functions on the Strophe namespace that cover the most common low-level tasks when working with XMPP: parsing and constructing JIDs, building and serializing XML elements, extracting text content, sanitizing HTML for XMPP-IM, and encoding or escaping strings. These functions are defined in src/utils.ts and src/log.ts and are re-exported directly on the Strophe global object.

JID Utilities

A Jabber ID (JID) has the form node@domain/resource. These functions parse each component out of a full or bare JID string. All functions return null when the requested component is not present in the JID.
Returns the bare JID (node@domain) by stripping the resource portion. If jid is falsy, returns null.
Strophe.getBareJidFromJid(jid: string): string | null
jid
string
required
A full or bare JID string, e.g. 'user@example.com/mobile'.
Strophe.getBareJidFromJid('user@example.com/mobile');
// → 'user@example.com'

Strophe.getBareJidFromJid('example.com');
// → 'example.com'
Returns the node (local) part of a JID — the portion before the @ sign. Returns null if there is no @ in the JID.
Strophe.getNodeFromJid(jid: string): string | null
jid
string
required
A JID string.
Strophe.getNodeFromJid('user@example.com/mobile');
// → 'user'

Strophe.getNodeFromJid('example.com');
// → null  (no @ sign)
Returns the domain portion of a JID. For a bare JID with no node, the entire string is the domain. For node@domain/resource, returns domain.
Strophe.getDomainFromJid(jid: string): string | null
jid
string
required
A JID string.
Strophe.getDomainFromJid('user@example.com/mobile');
// → 'example.com'

Strophe.getDomainFromJid('conference.example.com');
// → 'conference.example.com'
Returns the resource portion of a full JID — everything after the first /. Returns null for bare JIDs without a resource. Handles resources that themselves contain / characters.
Strophe.getResourceFromJid(jid: string): string | null
jid
string
required
A JID string.
Strophe.getResourceFromJid('user@example.com/mobile');
// → 'mobile'

Strophe.getResourceFromJid('user@example.com/path/with/slashes');
// → 'path/with/slashes'

Strophe.getResourceFromJid('user@example.com');
// → null
Escapes special characters in the node (local) part of a JID per XEP-0115 node escaping rules. Non-string values are returned unchanged.
Strophe.escapeNode(node: unknown): unknown
node
unknown
required
The JID node string to escape. If not a string, the value is returned as-is.
The following characters are escaped: \, space, ", &, ', /, :, <, >, @. Leading and trailing whitespace is also stripped.
Strophe.escapeNode('user@name');
// → 'user\\40name'

Strophe.escapeNode('first last');
// → 'first\\20last'
Reverses the escaping applied by escapeNode(). Non-string values are returned unchanged.
Strophe.unescapeNode(node: unknown): unknown
node
unknown
required
The escaped JID node string to unescape. If not a string, the value is returned as-is.
Strophe.unescapeNode('user\\40name');
// → 'user@name'

Strophe.unescapeNode('first\\20last');
// → 'first last'

XML Utilities

These functions create, copy, traverse, and serialize XML DOM elements. Strophe.js uses a shared internal Document for element creation to ensure cross-browser compatibility.
Returns the shared XML Document instance used internally by Strophe.js to create new elements. The document is lazily initialized on first call using document.implementation.createDocument('jabber:client', 'strophe', null).
Strophe.xmlGenerator(): Document
const doc = Strophe.xmlGenerator();
const elem = doc.createElement('presence');
You rarely need to call this directly. Use Strophe.xmlElement() to create elements — it uses xmlGenerator() internally.
Creates and returns a new XML DOM element. Attributes can be supplied as a key/value object, a two-dimensional array of [name, value] pairs, or omitted entirely. An optional text child can be added directly.
Strophe.xmlElement(
  name: string,
  attrs?: Array<Array<string>> | Record<string, string | number> | string | number,
  text?: string | number
): Element | null
name
string
required
The tag name for the new element. Returns null if name is falsy.
attrs
object | array | string | number
Optional attributes as an object { key: value }, an array [['key', 'value'], ...], or a shorthand text string/number (treated as text content when no text argument is provided).
text
string | number
Optional text content appended as a child text node.
Strophe.xmlElement('message', { to: 'user@example.com', type: 'chat' });
// → <message to="user@example.com" type="chat"/>
Creates a new XML DOM text node using the shared XML document.
Strophe.xmlTextNode(text: string): Text
text
string
required
The character content for the text node.
const textNode = Strophe.xmlTextNode('Hello');
elem.appendChild(textNode);
Parses a string as XML using DOMParser with MIME type 'text/xml' and returns the resulting XMLDocument. Useful for parsing raw XML strings received from the server.
Strophe.xmlHtmlNode(text: string): XMLDocument
text
string
required
A well-formed XML string to parse.
const doc = Strophe.xmlHtmlNode('<message to="user@example.com"><body>Hi</body></message>');
const body = doc.getElementsByTagName('body')[0];
Parses an XML string and returns its first element child. Throws a Parser Error if the XML is malformed. For message, iq, and presence elements, validates that the namespace is either 'jabber:client' or 'jabber:server'.
Strophe.toElement(
  string: string,
  throwErrorIfInvalidNS?: boolean
): Element
string
string
required
A well-formed XML string representing a single element.
throwErrorIfInvalidNS
boolean
When true, throws an Error if a top-level message, iq, or presence element has an unexpected namespace. When false (default), logs an error instead.
const elem = Strophe.toElement('<presence xmlns="jabber:client" type="available"/>');
console.log(elem.tagName); // 'presence'
Performs a deep copy of an XML DOM element, duplicating all attributes and child nodes recursively. Returns a new Element for element nodes, a new Text for text nodes, or undefined for other node types.
Strophe.copyElement(node: Node): Element | Text | undefined
node
Node
required
The DOM node to copy. Only ElementType.NORMAL (element) and ElementType.TEXT nodes are copied; other types return undefined.
const original = Strophe.xmlElement('message', { to: 'user@example.com' });
const copy = Strophe.copyElement(original);
// copy is an independent Element with the same attributes and children
Converts an HTML DOM node into a sanitized XHTML-IM-compliant XML node. Only tags, attributes, and CSS properties in the Strophe.XHTML allowlist are preserved. Disallowed elements are replaced with document fragments containing their sanitized children.
Strophe.createHtml(node: Node): Node | undefined
node
Node
required
An HTML DOM node to sanitize and convert. Handles element nodes (NORMAL), text nodes (TEXT), and document fragments (FRAGMENT).
// Sanitize a DOM node before embedding in an XMPP message
const htmlNode = document.querySelector('.message-body');
const xhtmlNode = Strophe.createHtml(htmlNode);

const msg = $msg({ to: 'user@example.com', type: 'chat' })
  .c('html', { xmlns: Strophe.NS.XHTML_IM })
  .c('body', { xmlns: Strophe.NS.XHTML })
  .cnode(xhtmlNode);
See the XHTML allowed values section in the Constants reference for the full list of permitted tags, attributes, and CSS properties.
Serializes an XML Element or Strophe Builder instance into a string. This is the canonical way to convert a stanza to a string for logging or raw transmission inspection.
Strophe.serialize(elem: Element | Builder): string
elem
Element | Builder
required
The element or builder instance to serialize.
const stanza = $msg({ to: 'user@example.com', type: 'chat' })
  .c('body').t('Hello');

console.log(Strophe.serialize(stanza));
// → '<message to="user@example.com" type="chat"><body>Hello</body></message>'
Iterates over child elements of elem, calling func for each child whose tag name matches elemName. If elemName is falsy (null or empty string), func is called for every child element node.
Strophe.forEachChild(
  elem: Element,
  elemName: string,
  func: (child: Element) => void
): void
elem
Element
required
The parent element whose children to iterate.
elemName
string
required
The tag name to filter by. Pass an empty string or null to iterate all child elements.
func
(child: Element) => void
required
Callback invoked with each matching child element.
// Iterate all <item> children of a roster query result
Strophe.forEachChild(queryElem, 'item', (item) => {
  console.log(item.getAttribute('jid'));
});
Compares an element’s tagName to name. The comparison is case-sensitive.
Strophe.isTagEqual(el: Element, name: string): boolean
el
Element
required
The DOM element to inspect.
name
string
required
The expected tag name (case-sensitive).
Strophe.isTagEqual(elem, 'message'); // true if elem.tagName === 'message'
Concatenates all text node values that are direct children of elem and returns the XML-escaped result. If elem itself is a text node with no children, returns its nodeValue. Returns null if elem is null.
Strophe.getText(elem: Node | null): string | null
elem
Node | null
required
The DOM node whose text content to extract.
const bodyElem = stanza.getElementsByTagName('body')[0];
const text = Strophe.getText(bodyElem);
// Returns the XML-escaped text content of the <body> element
The return value is XML-escaped (e.g. &amp; instead of &). If you need raw text, unescape it with Strophe.xmlunescape().

String Encoding

Escapes the five XML special characters in text so it can be safely embedded in XML content or attribute values.
Strophe.xmlescape(text: string): string
text
string
required
The plain string to escape.
CharacterEscape
&&amp;
<&lt;
>&gt;
'&apos;
"&quot;
Strophe.xmlescape('AT&T <example>');
// → 'AT&amp;T &lt;example&gt;'
Reverses the escaping applied by xmlescape(), converting XML entities back to their literal characters.
Strophe.xmlunescape(text: string): string
text
string
required
An XML-escaped string to unescape.
Strophe.xmlunescape('AT&amp;T &lt;example&gt;');
// → 'AT&T <example>'

XHTML Validation

These functions check whether a given tag name, attribute name, or CSS property name is permitted within the XHTML-IM profile defined by XEP-0071. They are used internally by Strophe.createHtml() but are also available for custom sanitization logic.
Returns true if tag is in the XHTML-IM allowed tag list.
Strophe.validTag(tag: string): boolean
tag
string
required
A lowercase HTML tag name to check (tag names are case-sensitive and must be lowercase).
Strophe.validTag('span');   // → true
Strophe.validTag('script'); // → false
Strophe.validTag('div');    // → false
Returns true if attribute is permitted on tag per the XHTML-IM profile.
Strophe.validAttribute(tag: string, attribute: string): boolean
tag
string
required
The lowercase tag name (must be a valid XHTML-IM tag).
attribute
string
required
The lowercase attribute name to check.
Strophe.validAttribute('a', 'href');   // → true
Strophe.validAttribute('a', 'class');  // → false
Strophe.validAttribute('img', 'src');  // → true
Returns true if the CSS property name style is in the XHTML-IM allowed CSS list.
Strophe.validCSS(style: string): boolean
style
string
required
A lowercase CSS property name (e.g. 'font-weight', 'color').
Strophe.validCSS('color');            // → true
Strophe.validCSS('font-weight');      // → true
Strophe.validCSS('border-radius');    // → false
See the Constants reference for the complete list of allowed CSS properties.

Logging

Strophe.js uses an internal logging system exposed via the Strophe namespace. All log calls are gated by the current log level set via setLogLevel(). Raw wire data (sent/received XML) is logged separately through Connection.rawInput and Connection.rawOutput callbacks.
Sets the minimum log level. Any log() call with a level below this threshold is silently discarded.
Strophe.setLogLevel(level: LogLevel): void
level
LogLevel
required
One of the Strophe.LOG_LEVELS values: 0 (DEBUG) through 4 (FATAL). Throws an Error if the value is outside this range.
// Show only warnings and above
Strophe.setLogLevel(Strophe.LOG_LEVELS.WARN);

// Show everything during development
Strophe.setLogLevel(Strophe.LOG_LEVELS.DEBUG);
Emits a log message at the specified level. Uses console.debug, console.info, console.warn, or console.error based on the level value.
Strophe.log(level: number, msg: string): void
level
number
required
The numeric log level. Use a Strophe.LOG_LEVELS constant.
msg
string
required
The message string to log.
Strophe.log(Strophe.LOG_LEVELS.INFO, 'Connection established');
Convenience shorthand methods that call Strophe.log() at the corresponding level.
Strophe.debug(msg: string): void   // → log(LOG_LEVELS.DEBUG, msg)
Strophe.info(msg: string): void    // → log(LOG_LEVELS.INFO, msg)
Strophe.warn(msg: string): void    // → log(LOG_LEVELS.WARN, msg)
Strophe.error(msg: string): void   // → log(LOG_LEVELS.ERROR, msg)
Strophe.fatal(msg: string): void   // → log(LOG_LEVELS.FATAL, msg)
msg
string
required
The message string to log.
Strophe.debug('Sending presence stanza');
Strophe.warn('Reconnect attempt 3 of 5');
Strophe.error('Unexpected server response format');
The different levels and their intended uses:
MethodLevelUse for
debug0Tracing execution, variable dumps during development
info1Normal operational events (auth succeeded, disconnect called)
warn2Transient issues (request timeout, retry attempt)
error3Problems requiring attention but potentially recoverable
fatal4Non-recoverable failures (stack traces, unhandled exceptions)

Global Utilities

Adds a new entry to the Strophe.NS namespace map. Useful for registering extension-specific namespaces used throughout your application.
Strophe.addNamespace(name: string, value: string): void
name
string
required
The property name to add to Strophe.NS. By convention, use uppercase (e.g. 'PING', 'MAM').
value
string
required
The full namespace URI string.
Strophe.addNamespace('PING', 'urn:ietf:params:xml:ns:xmpp-ping');
Strophe.addNamespace('MAM', 'urn:xmpp:mam:2');

// Now usable as:
const iq = $iq({ type: 'get' }).c('ping', { xmlns: Strophe.NS.PING });
Registers a connection plugin so that it is automatically initialized and attached to every new Connection instance as connection[name]. Plugins allow you to extend the Connection API without modifying the core library.
Strophe.addConnectionPlugin(name: string, ptype: object): void
name
string
required
The property name under which the plugin will be accessible on each connection instance (e.g. 'roster', 'ping').
ptype
object
required
The plugin prototype object. Must implement an init(connection) method that Strophe.js calls when attaching the plugin to a new connection.
const PingPlugin = {
  init(connection) {
    this._connection = connection;
    Strophe.addNamespace('PING', 'urn:ietf:params:xml:ns:xmpp-ping');
  },
  ping(jid, successCallback, errorCallback) {
    const id = this._connection.getUniqueId('ping');
    const iq = $iq({ type: 'get', to: jid, id })
      .c('ping', { xmlns: Strophe.NS.PING });
    this._connection.sendIQ(iq, successCallback, errorCallback);
  },
};

Strophe.addConnectionPlugin('ping', PingPlugin);

// After registration, every connection has:
const conn = new Strophe.Connection('wss://xmpp.example.com/ws');
conn.ping.ping('user@example.com', onSuccess, onError);
For a detailed walkthrough of building plugins, see the Plugins guide.

Build docs developers (and LLMs) love