Receiving messages in AngularJS with the help of Strophe.js

My XMPP client in AngularJS, inspired by this stackoverflow link.

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d282e382f1d282e382f7331323e3c31">[email protected]</a>
can send messages successfully, but
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f2f4e2f5c7f2f4e2f5a9ebe8e4e6eb">[email protected]</a>
doesn't receive them as expected when messaging from
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f5fafbe0fcf1e6d4e1e7f1e6baf8fbf7f5f8">[email protected]</a>
.

I'm unsure if I've implemented the addHandler and onMessage functions correctly. Can anyone offer assistance?

<html>
<head>
    <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
    <script type="text/javascript" src="strophe.min.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="init">
    </div>

    <script type="text/javascript">

    BOSH_SERVICE = 'http://localhost/http-bind';
    xmpp_user = "user";
    xmpp_domain = "user.local";
    xmpp_userdomain = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="add8dec8dfedd8dec8df83c1c2cecc91d3c4c8cac7">[email protected]</a>";
    xmpp_password = "userpassword";

    angular.
    module('myApp', []).
    controller('init', function(xmppAuth){
        xmppAuth.auth(xmpp_userdomain,xmpp_password);
    }).
    service('xmppAuth', function() {
        return {
            auth: function(login, password) {
               connect = new Strophe.Connection(BOSH_SERVICE);
               connect.connect(login, password, function (status) {
                   if (status === Strophe.Status.CONNECTED) {
                        console.log("Connection successful");

                        //trying to send message
                        var message = "Hello";
                        var to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1b0bfbea5b9b4a391a4a2b493dfaabda9bab295d7a0acaead">[email protected]</a>";
                        if(message && to){
                            var reply = $msg({
                                to: to,
                                type: 'chat'
                            })
                            .cnode(Strophe.xmlElement('body', message)).up()
                            .c('active', {xmlns: "http://jabber.org/protocol/chatstates"});
                            connect.send(reply);
                            console.log('Sent message to ' + to + ': ' + message);
                        }

                        //adding handler for receiving messages
                        connect.addHandler(onMessage, null, "message", null, null, null);
                        var onMessage = function (message){
                            console.log('Received message');
                            return true;
                        }

                   }
               })
            }
        }
    })

    </script>
</body>
</html>

Answer №1

UPDATE: I have successfully integrated the on_presence and on_message functions within the controller, resulting in successful functionality!

<html>
<head>
    <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
    <script type="text/javascript" src="strophe.min.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="init">
    </div>

    <script type="text/javascript">

    BOSH_SERVICE = 'http://localhost/http-bind';
    xmpp_user = "user";
    xmpp_domain = "user.local";
    xmpp_userdomain = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="354046504775404650471b595a565459">[email protected]</a>";
    xmpp_password = "userpassword";

    angular.
    module('myApp', []).
    controller('init', function(xmppAuth){
        xmppAuth.auth(xmpp_userdomain,xmpp_password);

        on_presence = function (presence){
            console.log('presence');
            return true;
        }

        on_message = function (message){
            //console.log('message');
            console.log(message);
            return true;
        }
    }).
    service('xmppAuth', function() {
        return {
            auth: function(login, password) {
               connect = new Strophe.Connection(BOSH_SERVICE);
               connect.connect(login, password, function (status) {
                   if (status === Strophe.Status.CONNECTED) {
                        console.log("auth pass");

                        //try send helo
                        var message = "helo";
                        var to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b8b7b6adb1bcab99acaabcabf7b5b6bab8b5">[email protected]</a>";
                        if(message && to){
                            var reply = $msg({
                                to: to,
                                type: 'chat'
                            })
                            .cnode(Strophe.xmlElement('body', message)).up()
                            .c('active', {xmlns: "http://jabber.org/protocol/chatstates"});
                            connect.send(reply);
                            console.log('I sent ' + to + ': ' + message);
                        }

                        //addhandler receive messg
                        connect.addHandler(onMessage, null, "message", null, null, null);
                        var onMessage = function (message){
                            console.log('message');
                            return true;
                        }

                   }
               })
            }
        }
    })

    </script>
</body>
</html>

Answer №2

Based on the link provided, it seems that upon successful authentication, you should set the presence status to online.

var handlePresence = function(presence) {
    // Perform some actions
    return true;
};

According to the XMPP protocol, it is possible that the recipient needs to be set as online before receiving any messages.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to continuously polling a GET request in JavaScript until the response status is successful

In my JavaScript code, I have a function that utilizes AJAX to send a GET request. The response from the request can be either success, fail, or in process if the job is still running. I want this function to continuously send the GET request every few s ...

Extra assistance might be required to manage the output from these loaders

I'm in the process of developing a State Management Library for ReactJs. However, when I integrate it into my React project (built with create-react-app), an error is thrown: Failed to compile. path/to/agile/dist/runtime.js 116:104 Module parse faile ...

Modal window closed - back to the top of the page

I am struggling with a simple modal popup window that does not maintain the scroll position when closed, instead returning you to the top of the page. I am looking for a way to keep it at the same scroll position without much knowledge of Javascript. You ...

Allowing certain routes to be processed by Groovy while others are managed by react-router v4

I'm currently dealing with a situation where the backend Groovy code contains controllers that render GSP (Groovy Server Pages), while for the frontend we're utilizing react-router v4 to manage routes. The issue that I am facing is that when defi ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...

Switch up the picture when you press on it

I have a task involving a table where I want to switch out an image in the <td> when it is clicked, using a URL that I specify beforehand. The URL of the image will be provided when clicking on a link within the page. For example: index.html?type=d ...

How should .has(), .get() and .set() be properly implemented for a JavaScript Map() within an ExpressJS server?

Feeling thrown off by javascript Map()? My query revolves around javascript Map() - the set, get, and has() functions. Despite thinking I was an expert, it seems I still have things to learn... Situation: I'm dealing with a 'global' map sto ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

Ways to retrieve the value of the chosen radio button using Prototype or JQuery

Looking for a way to retrieve the value of the selected radio button using either JQuery or Prototype? Check out this sample form: <label for="deliveryChoice">Courier&nbsp;<b>&pound;3.00</b></label> <input type="radio" ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

When refreshing, the useEffect async function will not execute

Upon page load, the getImages function is intended to run only once. After refreshing the page, both tempQuestionImages and questionImages are empty. However, everything works perfectly after a hot reload. I am utilizing nextJs along with Firebase Cloud ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

What is the best way to handle multiple axios calls with pagination in a React application?

Discussing React Pagination and Handling Multiple Axios Calls In my current project, I am faced with the challenge of mapping through an array of numbers and making sequential API calls for each one. The API I'm working with returns paginated results ...

Utilizing Angular to bind a variable as an index for another variable within markup

Is it possible to render an array element in AngularJs using another scope variable as the index like this: {{array[{{index}}]}}? For example, I am attempting to do this (note the nested {{}}): <ion-item collection-repeat="item in prodataSelect" colle ...

What is the process for obtaining an API Key in order to access a service prior to authorization?

Alright, I have this app. It's a versatile one - can run on mobile devices or JavaScript platforms. Works across Windows, Apple, and Android systems. The app comes equipped with a logging API that requires an API key for operation. Specifically, befo ...

What is the best way to merge two ajax functions into a single function?

I am looking to streamline my ajax functionality by combining two separate functions. One function is used to post a name, while the other is used to upload an image. I would like to create a single function that can handle both tasks of posting a name and ...

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? https://i.sstatic.net/y7Cs5.png Codesandbox: https: ...

Selected jQuery plugin is not updating HTML select option

I've been attempting to update the select tag in my HTML file to match the style used in the example on the Chosen v1.8.7 website, but despite following the instructions, the select element remains unchanged: test.html <head> <link rel=& ...

Importing JSON data into JavaScript

For the past few hours, I've been attempting to load a JSON file into JavaScript to feed map coordinates to the Google Maps service. Unfortunately, my script is incomplete and I cannot obtain any results. Here's what I have so far: <script&g ...

Looking for jQuery bbq... is the grill fired up yet?

In my exploration of the jQuery bbq plugin, I noticed that there is no reference to document.hash in the code. I believe that the function for retrieving the hash is located at line 1094: function get_fragment( url ) { url = url || location.href; ...