Parsing XML websocket responses with Strophe.js

假装没事ソ 提交于 2020-01-16 18:53:06

问题


I'm using Strophe.js to connect to an XMPP server via websockets. Here's a sample response I get when the connected user receives a message:

<message xmlns='jabber:client' xml:lang='en' to='agent@chat.domain.com/6665193359253278721998' from='client@chat.domain.com/Mac' type='chat' id='purple42fccc5c'> 
  <archived by='agent@chat.domain.com' id='1557026681122740' xmlns='urn:xmpp:mam:tmp'/>
  <stanza-id by='agent@chat.domain.com' id='1557026681122740' xmlns='urn:xmpp:sid:0'/>
  <active xmlns='http://jabber.org/protocol/chatstates'/> 
  <body>
    1
  </body>
</message>

Checked the docs, but I was unable to find anything useful on the subject. Does Strophe have a built-in way to extract the data I need from different types of messages? Or do I need something else?


回答1:


Once the connection is created you need to define hooks to receive the message and be able to interact with it:

connection.addHandler(onMessage, null, 'message', 'chat');
connection.addHandler(onMessage, null, 'message', 'groupchat');

And then, you just need to define the onMessage function.

onMessge: function(stanza) {
  $stanza = $(stanza);

  messageId = $stanza.attr('id') || null;
  to = $stanza.attr('to');
  from = $stanza.attr('from').toLowerCase();
  barejid = Strophe.getBareJidFromJid(from);

  type = $stanza.attr('type');
  bodies = $stanza.find('body');
  body = bodies.length ? Strophe.xmlunescape(Strophe.getText(bodies[0])) : '';
....

}

Hope it helped.



来源:https://stackoverflow.com/questions/56022820/parsing-xml-websocket-responses-with-strophe-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!