Search code examples
javascriptconverse.js

Reading custom stanzas in converseJS plugin?


Is it possible to receive custom stanzas in converse.js?

I tried to listen to incoming messages:

converse.plugins.add('dummy', {
  initialize: function() {
    var _converse = this._converse;

    _converse.api.listen.on('message', function(xmlMessage) {
      console.log('Received message!');
    });
  }
});

My custom stanza looks like this:

<message to='...' from='...' type='groupchat'>
    <custom_stanza>
        <created_at>2018-02-14T16:25:00+01:00</created_at>
        <store xmlns='urn:xmpp:hints'/>
    </custom_stanza>
</message>

But unfortunately this stanza won't get recognized here. Normal messages work.


Solution

  • I'm not sure why a message event isn't triggered for your custom message. There must be some assumption in the converse.js code which your custom message doesn't fulfill.

    Converse.js uses Strophe.js under the hood, so you can use Strophe's addHandler to register an event handler on a lower level.

    Here's how you would do this:

    converse.plugins.add('dummy', {
      initialize: function() {
        var _converse = this._converse;
    
        _converse.on('connected', () => {
    
          // _converse.connection is an instance of Strophe.Connection
          // which provides the `addHandler` method.
    
          _converse.connection.addHandler((message) => {
             // Your message handling code comes here...
    
          }, null, 'message');
       });
      }
    });
    

    An example of this usecase is in the converse-bookmarks.js plugin.