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

Switching between a secondary menu using ClassieJS or jQuery?

Currently, the code is configured to toggle the same menu for every icon. To see my current progress, you can check out this fiddle: http://jsfiddle.net/2Lyttauv/ My goal is to have a unique menu for each individual icon. I began by creating the followi ...

"Comparison: Java Installation vs. Enabling Java in Your Web Browser

Is there a method to determine if Java is currently running on your system or if it has been disabled in your browser? Our application relies on Java applets, and we typically use "deployJava.js" to load the applet. However, even when Java is disabled in t ...

Is it possible to dispatch actions from getters in Vuex?

Fiddle : here Currently, I am in the process of developing a web application using Vue 2 with Vuex. Within my store, I aim to retrieve state data from a getter. My intention is for the getter to trigger a dispatch and fetch the data if it discovers that t ...

Exploring Tmbd Movie Database with React.js - Results of searches will only display after the application is recompiled

Presented here is my component. The challenge I am facing pertains to the fact that upon entering a search query, no results are displayed until I manually save in the code editor and trigger a recompilation of the application. Is there a more efficient ap ...

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

Incorporate a JavaScript variable within the src attribute of a script tag

Embedding Google's script allows for displaying a trends Map on our website. <script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&a ...

Error message received from GitHub when attempting to create a repository through the REST API states that JSON cannot

I am currently in the process of learning how to use REST APIs for GitHub, and my current project involves creating a new repository using JavaScript. Below is the function I have written for this purpose, which includes generating a token and granting all ...

What method is used to initialize the variables in this JavaScript snippet, and what other inquiries are posed?

As a backend developer, I'm looking to understand this JavaScript snippet. While I grasp some parts and have added comments where I am clear, there are still sections that leave me with bold questions. function transformData (output) { // QUESTIO ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...

Converting Variable Values to Element IDs in JavaScript: A Helpful Guide

Is it possible to declare a value in variable A and then access that value as an id in variable B using the method getElementById()? var A = 10; var B = document.getElementById(A); console.log(B); ...

Issue with inconsistent functionality of Socket.io

I've encountered an issue while working with multiple modules - specifically, socket.io is not functioning consistently... We have successfully implemented several 'routes' in Socket.io that work flawlessly every time! However, we are now ...

Welcome to the launch of OpenWeatherMap!

I just signed up for an account on the OpenWeatherMap website. My goal is to retrieve the current weather information for a specific location using the City ID API Call: http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey How ca ...

Connect a function to create a new document element in order to modify the

I am attempting to intercept document.createElement in order to modify the value of the src property for each assignment. My current approach involves: var original = document.createElement; document.createElement = function (tag) { var element ...

When attempting to use jQuery to click on a button that triggers an ajax callback, the functionality does not

I am facing an issue with my Drupal website. I have created a form with a button that has an ajax callback. The callback works perfectly, but now I want to execute a small JavaScript function when the user clicks on the submit button. Instead of creating ...

Sharing application state between different routes in React Router v4 can be achieved by using methods such

I'm seeking solutions to address the following challenge: Without utilizing any state management library, I solely rely on React. The primary application state is contained within the <MyFoodApp/> component, which includes an array of restaura ...

Random crashes are observed in Selenium tests during the execution of JavaScript code

Currently, I am in the process of writing functional tests for a Zend application. These tests are executed using PHPUnit and a wrapper called https://github.com/chibimagic/WebDriver-PHP In order to handle the extensive use of JavaScript and AJAX in the a ...

What is the reason for React.Component being implemented as a function rather than an ES6 class?

After delving into the codebase of React, I made an interesting discovery. When you define a class like class App extends React.Component, you are essentially extending an object that is generated by the following function: function Component (props, cont ...

Utilizing AngularJS: Using ng-click with ng-repeat to retrieve all data simultaneously

Having a simple ng-repeat: <div ng-repeat="x in names"> <h4>{{x.productid}}</h4> <h4>{{x.newquantity}}</h4> <h4>{{x.total}}</h4> <button ng-click="addInfoAboutOrder(x)">Add Info</button> ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...