问题
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