Cordova inAppBrowser store and reuse credentials - javascript

The case:
I have a simple cordova app that opens the mobile version of a (Drupal 7) website using the inAppBrowser plugin. On the website, a user can log in to read more content. Also everyone that has the app installed, can get push notifications if accepted.
The problem: Users who have logged in are being logged out after a while. It happens on both iOS and Android.
Now I would like is that the app stores the filled in value of the username and password. So when the user is being logged out it has it's credentials filled in. Is anyone able to help?
I have found a few similar question on the web, but I can't seem to get it to work using localStorage.
This is a snippet I found in this question. But I can't get it to work. the edit-name and edit-pass are the id's of the input fields on the website.
function loadStopped() {
var username = "";
if (localStorage.getItem("username") !== null) {
username = localStorage.getItem("username");
}
var password = "";
if (localStorage.getItem("password") !== null) {
password = localStorage.getItem("password");
}
document.getElementById("edit-name").value = username;
document.getElementById("edit-pass").value = password;
document.getElementById("the_form").addEventListener("submit", function() {
localStorage.setItem("username", document.getElementById("edit-name").value);
localStorage.setItem("password", document.getElementById("edit-pass").value);
});
}
My full code:
var app = {
// Application Constructor
browser: null,
host: 'http://www.somewebsite.com/',
initialize: function () {
this.bindEvents();
},
// Bind Event Listeners
bindEvents: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
onDeviceReady: function () {
app.checkConnection();
app.initPushwoosh();
},
checkConnection: function () {
var networkState = navigator.connection.type;
var states = {};
states[Connection.NONE] = 'no connection';
//if no connection show popup
if (networkState === Connection.NONE) {
navigator.notification.alert(
'Please enable your internet connection\nand restart the app', // message
function () {
}, // callback
'Oops no internet', // title
'Ok' // buttonName
);
//if network is found, launch inappbrowser
} else {
app.openBrowser('/');
}
},
openBrowser: function (url) {
function loadStopped() {
var username = "";
if (localStorage.getItem("username") !== null) {
username = localStorage.getItem("username");
}
var password = "";
if (localStorage.getItem("password") !== null) {
password = localStorage.getItem("password");
}
document.getElementById("edit-name").value = username;
document.getElementById("edit-pass").value = password;
document.getElementById("the_form").addEventListener("submit", function() {
localStorage.setItem("username", document.getElementById("edit-name").value);
localStorage.setItem("password", document.getElementById("edit-pass").value);
});
}
if (url.indexOf('/') !== 0) {
url = '/' + url;
}
url = this.updateQueryStringParameter(url, 'app_os', 'mobile');
window.open = cordova.InAppBrowser.open;
this.browser = cordova.InAppBrowser.open(this.host + url, '_blank', 'location=no,hidden=no');
this.browser.addEventListener('loadstop', loadstopped);
this.browser.addEventListener('loadstop', function(e)){
var username="";
if (localStorage.getItem("username") !== null){
username = localStorage.getItem("username");
}
this.browser.executeScript({
code:"document.getElementById('edit-name').value;"
});
});
this.browser.addEventListener('exit', function (e) {
if (navigator.app) {
navigator.app.exitApp();
} else if (navigator.device) {
navigator.device.exitApp();
} else {
window.close();
}
});
},
// Update DOM on a Received Event
receivedEvent: function (id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
updateQueryStringParameter: function(uri, key, value) {
// remove the hash part before operating on the uri
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value) {
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([&]?)" + key + "=.*?(&|$)", "i"), '');
if (uri.slice(-1) === '?') {
uri = uri.slice(0, -1);
}
} else if (uri.match(re)) {
uri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
uri = uri + separator + key + "=" + value;
}
return uri + hash;
}
};
app.initialize();
Anyone who could tell me what I'm doing wrong or can give me a detailed 'guide' of how I can get it to work?
Thanks a lot in advance!

Related

Return text when checkbox selected

In my site, I have a form that users can click on a checkbox to select "available". I want to have "Yes" or "No" returned in the displayArticle function based on whether the box is checked or not. Right now it returns True or False, which is not optimal. How can I code this?
Here is my entire JS code:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('RentalContract.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.RentalContract = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.RentalContract.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.RentalContract.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5], article[6], article[7]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
//displayArticle: function(id, seller, beds, baths, propaddress, rental_price, property_type, description, available, contact_email) {
displayArticle: function(id, seller, propaddress, rental_price, description, available, contact) {
var articlesRow = $('#articlesRow');
//var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(propaddress);
//articleTemplate.find('.beds').text(beds);
//articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text('$' + rental_price);
//articleTemplate.find('.property_type').text(property_type);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact').text(contact);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
// articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
//var _beds = $('#beds').val();
//var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
//var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact = $('#contact').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
// if((_description.trim() == '') || (rental_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.RentalContract.deployed().then(function(instance) {
//return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
return instance.sellArticle(_propaddress, _rental_price, _description, _available, _contact,{
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.RentalContract.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._propaddress + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._propaddress + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.RentalContract.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
If I understand what you're trying to do, perhaps this will work for you.
var isChecked = '';
if (articleTemplate.find('.available').checked === true)
{ isChecked = 'yes'} else
{ isChecked = 'no'}
.
.
.
return isChecked;
Do this:
articleTemplate.find( '.available' ).text( available ? 'Yes' : 'No' );
Example:
function returnValue() {
$( '#val' ).text( $( '#chk' ).is( ':checked' ) ? 'Yes' : 'No' )
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" onclick="returnValue()" />
<label for="chk">Available</label>
<h2 id="val"></h2>

Get the name of the uploaded file

I am new to AngularJS1 and Js. Here i am uploading a file which will be saved on my drive as well as in mongodb. What I am trying to do is to get the uploaded file name which can easily be seen here in attached picture. Kindly help me out with this.
$scope.uploadedFileList.push(p);
$('#addproFile').ajaxfileupload({
action: 'http://' + window.location.hostname + ':' + window.location.port + '/api/upload',
valid_extensions : ['md','csv','css', 'txt'],
params: {
dummy_name: p
},
onComplete: function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
/* $scope.nameString = uploadedFileList.join(',');
$scope.$apply();*/
},
onCancel: function() {
console.log('no file selected');
}
});
This is my controller
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true == settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
} else {
uploading_file = false;
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery )
this is my ajax file upload function

Unwanted google smart lock

I've got some javascript code in an application that automatically requests through an iframe and hardcoded credentials an id_token and access_token to an openid connect/oauth2 endpoint.
The problem is that, although the user does not get to see the form because it happens silently, google smart lock prompts the user to save the credentials, which is undesirable (mainly because they are hardcoded and don't need to be remembered, and because we don't want users to see this).
Is there any way to prevent from code to google smart lock from displaying or any workaround to avoid this?
This is the code that gets executed with the hardcoded credentials.
TokenManager.prototype.login = function(username, password, rememberMe) {
var mgr = this;
var formHtml = '<form name="form" id="loginForm" method="post" style="display: none"></form>';
var form = $(formHtml).appendTo("body");
form.attr("action", this.settings.loginUrl + '?signin=' + this.signinId());
form.attr("target", this.settings.frameName);
var a = $('<input name="idsrv.xsrf" type="hidden">').appendTo(form);
var u = $('<input name="username" id="username" type="text">').appendTo(form);
var p = $('<input id="password" name="password" type="password">').appendTo(form);
var r = $('<input type="checkbox" id="rememberMe" name="rememberMe">').appendTo(form);
var btn = $('<button type="submit" style="display: none"></button>').appendTo(form);
u.val(username);
p.val(password);
r.val(rememberMe);
var checked = '';
if (rememberMe) {
checked = 'checked';
}
r.attr('checked', checked);
a.val(getCookie(TokenManager.xsrfKey));
var oauth = new OAuthClient(this.settings);
var frame = new FrameLoader('', this.settings.frameName);
frame.load(function (data) {
form.remove();
if (data.type === 'login') {
setCookie(TokenManager.xsrfKey, data.model.antiForgery.value, 1);
setCookie(TokenManager.signInKey, data.signin, 1);
this.showLogin(data.model, username);
} else
if (data.type === 'tokenCallback') {
var result = oauth.readImplicitResult(data.hash);
if (!result.error) {
var token = Token.fromOAuthResponse(result);
this.saveToken(token);
this.callTokenObtained();
}
} else {
if (data.type === 'error') {
var request = oauth.createImplicitRequest();
frame = new FrameLoader(request.url, mgr.settings.frameName);
frame.load(function(d) {
if (d.type === 'login') {
setCookie(TokenManager.signInKey, d.signin, 1);
setCookie(TokenManager.xsrfKey, data.model.antiForgery.value, 1);
setTimeout(function() {
mgr.login(username, password, rememberMe);
}, 0);
} else
if (d.type === 'tokenCallback') {
var result = oauth.readImplicitResult(d.hash);
if (!result.error) {
var token = Token.fromOAuthResponse(result);
mgr.saveToken(token);
mgr.callTokenObtained();
}
}
});
}
}
}.bind(this), function() {});
btn.click();
}
and this is the FrameLoader.js that is being used
define(['jquery'], function ($) {
function FrameLoader(url, frameName) {
this.url = url;
this.frameName = frameName;
}
FrameLoader.prototype.load = function(success, error) {
var frameHtml = '<iframe name="' + this.frameName + '" style="display:none"></iframe>';
var frame = $(frameHtml).appendTo("body");
function cleanup() {
window.removeEventListener("message", message, false);
if (handle) {
window.clearTimeout(handle);
}
handle = null;
frame.remove();
}
function cancel(e) {
cleanup();
if (error) {
error();
}
}
function message(e) {
if (handle && e.origin === location.protocol + "//" + location.host) {
cleanup();
if (success) {
success(e.data);
}
}
}
var handle = window.setTimeout(cancel, 10000);
window.addEventListener("message", message, false);
if (this.url)
frame.attr("src", this.url);
};
return FrameLoader;
});

How do I get a return value from a Handler function in JavaScript?

I am able to get the information from the object I am using to store the form information, when the one tries to fire the submit without filling in the fields successfully, but when I enter all the information correctly I can't seem to obtain the same upon success?
var theForm = document.getElementsByTagName('form')[0];
var firstNameInput = document.getElementById('firstNameInput');
var lastNameInput = document.getElementById('lastNameInput');
var emailInput = document.getElementById('emailInput');
var stateInput = document.getElementById('stateInput');
var theButton = document.querySelector('input[type=submit]');
// Wire the form's submit event to a callback
theForm.addEventListener('submit', validate);
function validate(e) {
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var formData = {
'firstName': null,
'lastName': null,
'email': null,
'stateInput': null
}
if ((firstNameInput.value == '') || (firstNameInput.value == null)) {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if ((lastNameInput.value == '') || (lastNameInput.value == null)) {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if ((stateInput.value == 'selectstate')) {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
console.log('There is no data from the form: ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return false;
} else {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
console.log('There is now data from the form: :) ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return true;
}
}
I tried this:
var result = theForm.addEventListener('submit', validate);
if (result) {
console.log(result);
}
Any help would be appreciated!
According to w3schools.com, this function, addEventListener() does not return anything.
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
If you'd like to know if the event listener is installed properly, you need to check if the function exists:
if(theForm.addEventListener){
theForm.addEventListener('submit', validate);
}else{
theForm.attachEvent('onclick', validate);
}

Retrieve messages on Page load Strophe js

I am trying to retrieve the messages whenever Uses logs in and the page loads. Right now I can able to retrieve the messages whenever the User sends the message to other User i.e., with the onMessage function.
Here is my code:
var archive = [];
// Retrives the messages whenever User sends the messages to Other User.
// TODO: Should be better when User logins and page loads
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0]),
avatar:'images/default_avatar_image.png'
};
archive.val(archive.val() + msg_data.from + ":" + msg_data.message + "\n" + msg_data.to + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q,data:data,response:response});
}
};
console.log('xmpp.history.start',{query:q});
function onMessage(msg) {
// Calls whenever User receives the messages
// and shows the received message in messagebox
var fromJid = msg.getAttribute("from"),
bareFromJid = Strophe.getBareJidFromJid(fromJid),
type = msg.getAttribute("type"),
elems = msg.getElementsByTagName("body");
if (type == "chat" && elems.length > 0) {
var body = elems[0],
message = Strophe.getText(body);
showMessage(bareFromJid + ": " + message);
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}
return true;
}
function send() {
// Calls whenever User sends the messages
// and shows the message in messagebox
var to = $('#to-jid').get(0).value,
myBareJid = Strophe.getBareJidFromJid(connection.jid);
message = $('#message').val(),
reply = $msg({to: to, type: 'chat'})
.c("body")
.t(message);
connection.send(reply.tree());
showMessage(myBareJid + ": " + message);
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
archive = $("#archive-messages");
archive.val("");
connection.rawInput = function (data) { log('RECV: ' + data); };
connection.rawOutput = function (data) { log('SEND: ' + data); };
Strophe.log = function (level, msg) { log('LOG: ' + msg); };
$("#send").bind('click', send);
});
So what happens in my code is whenever User receives the message, then all the messages be retrieved between those two Users.
How can I retrieve the messages in the chat box when I clicked on the particular User??
There were two issues in this. One is when I perform auto login with login() method when scripts loads, it at least takes 800ms to login and perform other actions. At this point I was facing the issue and also bit jQuery part.
Here is my code:
// Retrives the messages between two particular users.
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0])
};
var login_user = connection.jid.split('#')[0];
var username = msg_data.from.split('#')[0];
if(login_user == username) {
archive.val(archive.val() + "me:".capitalizeFirstLetter() + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
else {
archive.val(archive.val() + username.capitalizeFirstLetter() + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q, response:response});
}
};
$("#to-jid").change(function() {
$("#archive-messages").val("");
var to = {"with": $(this).val()};
$.extend(q, to);
// It takes around 800ms to login. So after this timeout we have to retrieve the messages of particular User.
setTimeout(function(){
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}, 1000);
});

Categories