Ionic cant get Reg ID for GCM - javascript

I read every topic and tried every way. About 2 days and i still didnt get Reg ID. MY Sender ID is right and check every example in real device. Also i tried
this one
this one
this one
this one
And thoses are just some pages. I almost tried everything and still get just okey message in success handler. Can someone tell me where is my mistake ?
var xxx = angular.module('starter', ['ionic', 'ngCordova'])
xxx.run(function ($ionicPlatform, $cordovaPush) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
var androidConfig = {
"senderID": "5757xxxxxxx",
};
document.addEventListener("deviceready", function () {
$cordovaPush.register(androidConfig).then(function (result) {
alert(result);
}, function (err) {
alert(err);
})
$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
switch (notification.event) {
case 'registered':
if (notification.regid.length > 0) {
alert('registration ID = ' + notification.regid);
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
// WARNING: dangerous to unregister (results in loss of tokenID)
$cordovaPush.unregister(options).then(function (result) {
// Success!
}, function (err) {
// Error
})
}, false)
});
});

Related

document.querySelector().getAttribute() didn't get fresh content meta name

I tried to implement codeigniter with $config['csrf_regenerate'] = TRUE;
I create code with combining javascript XMLHttpRequest & Jquery $.ajaxPrefilter.
I make a function for getting new csrf_hash from Codeigniter and append to meta name on HTML head.
At first request everything seems working.
But next request a got message 403 Forbidden because ajax send an old csrf hash.
Please fix my code.
I want before sending a POST request, ajax get new csrf hash form meta name on HTML head.
Sorry for my bad English.
Best Regards,
This is my code
$.ajaxPrefilter(function( options, originalOptions, jqXHR )
{
get_csrf_hash(callback => document.querySelector('meta[name="csrf_hash"]').setAttribute("content", callback) ); // It Work!!.. Get new csrf_hash and update content meta name.
if (options.type.toLowerCase() === "post")
{
options.data = $.param($.extend(originalOptions.data, { csrf_simpeg_v2 : document.querySelector('meta[name="csrf_hash"]').getAttribute("content")})); // Not Work didn't send fresh csrf hash
}
var originalSuccess = options.success;
options.success = function(data)
{
if (originalSuccess != null)
{
originalSuccess(data);
}
}
var originalError = options.error;
options.error = function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR.status + ' ' + jqXHR.statusText);
if(jqXHR.status == 401 || jqXHR.status == 403)
{
alert(jqXHR.status + ' ' + jqXHR.statusText);
}
else
{
if(originalError != null)
{
originalError();
}
}
};
});
function get_csrf_hash(callback)
{
var url = baseURL + 'login/get_csrf_token';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == XMLHttpRequest.DONE)
{
console.log(xhr.responseText);
return callback(xhr.responseText);
}
}
xhr.open('GET', url, true);
xhr.send(null);
}
$(function () {
});
get_csrf_hash is an asynchronous function, meaning that the JavaScript runtime will not wait for it to finish its task before moving on to executing the next lines. You need to put all the code that depends on the first AJAX request inside the callback:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
get_csrf_hash(callback => {
document.querySelector('meta[name="csrf_hash"]').setAttribute('content', callback);
if (options.type.toLowerCase() === 'post') {
options.data = $.param(
$.extend(originalOptions.data, {
csrf_simpeg_v2: document.querySelector('meta[name="csrf_hash"]').getAttribute('content')
})
);
}
var originalSuccess = options.success;
options.success = function(data) {
if (originalSuccess != null) {
originalSuccess(data);
}
};
var originalError = options.error;
options.error = function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.status + ' ' + jqXHR.statusText);
if (jqXHR.status == 401 || jqXHR.status == 403) {
alert(jqXHR.status + ' ' + jqXHR.statusText);
} else {
if (originalError != null) {
originalError();
}
}
};
});
});
You should look into the Fetch API and Promises. They will greatly simplify writing code like this. Here is the get_csrf_hash re-written using those tools:
function get_csrf_hash(callback) {
fetch('login/get_csrf_token')
.then(res => res.text())
.then(text => callback(text));
}

Twilio chat events memberUpdated, and userInfoUpdated never fired

i'm looking on what cases are these events is firing, i have implement it on these code
jQuery(document).ready(function() {
var chatChannel;
var chatClient;
var username;
var $input = $('#chat-input');
$.post("/tokens", function(data) {
username = data.username;
chatClient = new Twilio.Chat.Client(data.token);
chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel);
});
function createOrJoinGeneralChannel() {
// Get the general chat channel, which is where all the messages are
// sent in this simple application
// print('Attempting to join "general" chat channel...');
var promise = chatClient.getChannelByUniqueName("#{params[:chat_channel]}");
promise.then(function(channel) {
chatChannel = channel;
console.log("#{params[:chat_channel]} is exist");
console.log(chatChannel);
setupChannel();
return channel.getMembers();
// $input.removeClass('.hidden')
})
.then(function(members){
members.forEach(function(member){
console.log('member', member);
member.on('userInfoUpdated', function(){
console.log('userInfoUpdated', member);
})
})
})
.catch(function() {
// If it doesn't exist, let's create it
console.log("creating #{params[:chat_channel]} channel");
chatClient.createChannel({
uniqueName: "#{params[:chat_channel]}",
friendlyName: 'General Chat Channel'
}).then(function(channel) {
console.log("Created #{params[:chat_channel]} channel:");
console.log(channel);
chatChannel = channel;
setupChannel();
});
});
}
function setupChannel() {
chatChannel.join().then(function(channel) {
printMessage(username + ' joined the chat.');
chatChannel.on('typingStarted', showTypingStarted);
chatChannel.on('typingEnded', hideTypingStarted);
chatChannel.on('memberJoined', notifyMemberJoined);
chatChannel.on('memberLeft', notifyMemberLeft);
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
});
chatChannel.on('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
}
function updateMemberMessageReadStatus(member){
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
}
function leaveCurrentChannel() {
if (chatChannel) {
chatChannel.leave().then(function (leftChannel) {
console.log('left ' + leftChannel.friendlyName);
leftChannel.removeListener('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
leftChannel.removeListener('typingStarted', showTypingStarted);
leftChannel.removeListener('typingEnded', hideTypingStarted);
leftChannel.removeListener('memberJoined', notifyMemberJoined);
leftChannel.removeListener('memberLeft', notifyMemberLeft);
leftChannel.removeListener('memberUpdated', updateMemberMessageReadStatus);
});
}
}
function showTypingStarted(member) {
console.log('somebody is typing');
$('#is_typing').html(member.identity + ' is typing...');
}
function hideTypingStarted(member) {
$('#is_typing').html('');
}
function notifyMemberJoined(member) {
console.log('notifyMemberJoined');
printMessage(member.identity + ' joined the channel');
}
function notifyMemberLeft(member) {
console.log('notifyMemberLeft');
printMessage(member.identity + ' left the channel');
}
$input.on('keydown', function(e) {
if (e.keyCode == 13) {
chatChannel.sendMessage($input.val());
$input.val('');
} else {
//console.log('typing');
chatChannel.typing();
}
});
window.addEventListener("beforeunload", function (e) {
// var confirmationMessage = "\o/";
(e || window.event).returnValue = leaveCurrentChannel(); //Gecko + IE
return leaveCurrentChannel(); //Webkit, Safari, Chrome
});
});
and i've take alook to the console to see if my
console.log('userInfoUpdated', member);
or these guys
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
and they are never fired, during my test on the chat events, and i'm confused on how exactly i'm going to display how my users online or the status of a message is read or unread
so please enlighten me on the case, thank you
Twilio developer evangelist here.
According to the JS docs for the latest version of Twilio Chat, the event you need to listen for on members is just called 'updated'. So, listening for 'userInfoUpdated' won't work.
I would also recommend that within this code:
chatChannel.join().then(function(channel) {
//...
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
you use the channel passed to the callback, rather than the original chatChannel object. Like this:
chatChannel.join().then(function(channel) {
//...
channel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
I don't know if this will fix the issue, but I can't think of anything else right now.

CasperJS - Screen capture returns black image & test case does not find element when target url is not localhost

I am using CasperJs along with Phantomjs 1.9.8. I am testing a site which uses windows authentication. I am testing a version which is deployed on a remote server and locally.
Here is the test case.
var baseUrl = "http://SNG09034236:9999"; //For testing app on remote server
//var baseUrl = "http://localhost:9999"; //For testing app locally
casper.options.viewportSize = {
width: 1024,
height: 800
}
casper.pageSetting = {userName: 'myuid', password:pwd};
casper.options.waitTimeout = 5000;
casper.on('resource.requested', function(requestData, networkRequest) {
//console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData) + "\n");
});
casper.on("resource.received", function(response){
// console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response) + "\n");
});
casper.test.begin('Connecting to application', function suite(test) {
casper.start(baseUrl, function() {
document.querySelector("body").style.height = "700px";
this.echo("TITLE : ====> " + this.getTitle());
this.captureSelector('c:\\temp\\myImage.png', 'html');
})
.then(function(){
test.assertTitle("My app", "Title is correct");
})
.waitForSelector("#showUser",
function success() {
test.assertExists("#showUser", "Shadow button found");
this.click("#showUser");
},
function fail() {
console.log('Shadow button NOT found');
test.assertExists("#showUser");
})
.waitForSelector("#show-window-body",
function success() {
test.assertExists("#show-window-body", "Show div found");
this.click("#show-window-body");
},
function fail() {
test.assertExists("#show-window-body");
})
.waitForSelector("input[name='search_user-inputEl']",
function success() {
test.assertExists("input[name='search_user-inputEl']", "Show text box found");
this.click("input[name='search_user-inputEl']");
this.sendKeys('#search_user-inputEl', 'tomjspn3');
},
function fail() {
test.assertExists("input[name='search_user-inputEl']");
})
.waitForSelector("li",
function success() {
test.assertExists("li", "User found");
this.click("li");
},
function fail() {
test.assertExists("li", "User NOT found");
})
.run(function() {
casper.echo("TESTS COMPLETED");
casper.exit();
});
});
Issues:
this.captureSelector('c:\\temp\\myImage.png', 'html'); always returns a black image file (for site hoested locally and remotely ). But if test another site (google.com etc), I get the correct screenshot.
In the test case I am searching for showUser div. When the run the test case targeting a site which is hosted on local box, everything works fine and when I run same test case by changing the URL to a remote server, system cannot find the showUser div and does not produce any result.
Actually after adding the various hooks I can see following error when connecting to remote site:
Response (#1, stage "end"): {"contentType":null,"headers":[],"id":1,"redirectUR
":null,"stage":"end","status":401,"statusText":"Authorization Required","time":
2015-12-03T17:26:15.691Z","url":"http://SNG09034236:9999/"}
ResourceError: {
"errorCode": 5,
"errorString": "Operation canceled",
"id": 0,
"url": "http://SNG09034236:9999/"
}
I have also changed casper.pageSetting to casper.options.pageSetting

Ionic Push Android push notification returning "undefined" message

I've been trying to get Android push notifications working for my app for a little while now (iOS already completed) and have everything sorted out besides just getting the notification to actually show up on the Android device.
Registering the device id's, and pushing to the GCM server all seem to be working fine, but when I test what the message in the response back from GCM is returning I keep getting undefined.
All responses when pushing the message to GCM are success, correct device id's, a message id associated with it etc. Anyone able to point me in the right direction? Below you will see the code snippet with just a sample "alert" being used to display what is coming back that will end up being used as the notification in the "push".
This alert
alert('message = ' + e.message + ' payload message: ' + e.payload.message +
' e payload msgcnt: ' + e.payload.msgcnt + ' e.msg: ' + e.msg);
doesn't seem to be getting anything back to display the push.
function onDeviceReady() {
console.log('deviceready');
try {
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android' || device.platform == 'amazon-fireos') {
console.log('PN register');
pushNotification.register(successHandler, errorHandler, {
"senderID": "177718756870",
"ecb": "onNotification"
}); // required!
console.log('after PN register');
} else {
console.log('PN register');
pushNotification.register(tokenHandler, errorHandler, {
"badge": "true",
"sound": "true",
"alert": "true",
"ecb": "onNotificationAPN"
}); // required!
console.log('after PN register');
}
}
catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
console.log("ERROR", txt);
}
}
var pushNotification;
// handle GCM notifications for Android
window.onNotification = function(e) {
console.log('EVENT RECEIVED ' + e.event)
console.log("regID BEFORE CHECKS = " + e.regid);
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0)
{
console.log("regID = " + e.regid);
var data =
{
'device_id': e.regid,
'platform': device.platform,
'os_version': device.version,
'app_version': lawnmowerConfig.versionString,
'device_model': device.model
};
localStorage.setItem('push_data', JSON.stringify(data));
}
break;
case 'message':
console.log('Inside case message: ' + e.regid)
if (e.foreground)
{
// Add something to play a sound once working
}
else
{
if (e.coldstart) {
console.log("coldstart");
}
else {
console.log("not coldstart");
}
}
alert('message = ' + e.message + ' payload message: ' + e.payload.message + ' e payload msgcnt: ' + e.payload.msgcnt + ' e.msg: ' + e.msg);
break;
case 'error':
alert('GCM error = ' + e.msg);
break;
default:
// Testing using these alerts instead
alert('An unknown GCM event has occurred');
break;
}
};
function tokenHandler (result) {
console.log('push token handler');
console.log(result);
var data =
{
'device_id': result,
'platform': device.platform,
'os_version': device.version,
'app_version': lawnmowerConfig.versionString,
'device_model': device.model
};
localStorage.setItem('push_data', JSON.stringify(data));
}
function successHandler (result) {
console.log('success handler push success');
console.log("result: " + result);
}
function errorHandler (error) {
console.log('push error');
}
document.addEventListener('deviceready', onDeviceReady, true);
Registering the device id's, and pushing to the GCM server all seem to be working fine, but when I test what the message in the response back from GCM is returning I keep getting undefined.
It means that when you are testing "what the message .... is" you are referencing a variable not yet defined. In this line:
alert('message = ' + e.message + ' payload message: ' + e.payload.message +
' e payload msgcnt: ' + e.payload.msgcnt + ' e.msg: ' + e.msg);
there is no variable e.message. The data that you send from your server is attached to e.payload and value of e.event is set to message. I think your problem can be solved if you remove e.message. Something like:
alert('event = ' + e.event + ' payload message: ' + e.payload.message +
' e payload msgcnt: ' + e.payload.msgcnt + ' e.msg: ' + e.msg);
Note To detect variable issues (scope and/or declaration), debug one variable at a time. This will help you to precisely identify a problem and trace it to its origin.
I would advise you to use
alert("Payload message: " + e.payload.message);

Message callback synchronization error

In my extension's content script, I request data from background.js like so:
fireOnNewTopic (); // Initial run on cold start or full reload.
window.addEventListener ("hashchange", fireOnNewTopic, false);
function fireOnNewTopic () {
/*-- For the pages we want, location.hash will contain values
like: "#!newtopic/{group title}"
*/
if (location.hash) {
var locHashParts = location.hash.split ('/');
if (locHashParts.length > 1 && locHashParts[0] == '#!newtopic') {
var subjectStr = '';
var bodyStr = '';
switch (locHashParts[1]) {
case 'opencomments-site-discussions':
chrome.extension.sendMessage({name:"domain"},
function(response)
{
subjectStr = response.domain;
});
chrome.extension.sendMessage({name:"url"},
function(response)
{
bodyStr = "URL of last page visited: " + response.url;
});
break;
default:
break;
}
if (subjectStr && bodyStr) {
runPayloadCode (subjectStr, bodyStr);
}
}
}
}
Unfortunately, since sendMessage() runs asynchronously with the callback, at the time the code reaches runPayloadCode(), subjectStr and bodyStr are still null, since the code in background.js hasn't completed. What's the best way to synchronize the code so that subjectStr and bodyStr are filled in by the time runPayloadCode() is called?
To elaborate on what Sudarshan said about combining the two requests into one (sorry, need code so couldn't just comment) here's what you could do...
send
chrome.extension.sendMessage({url: true, domain:true}, function(response) {
console.debug('The url is "'+response.url+'" and the domain is"'+response.domain+'"');
if (repsone.url && response.domain) {
runPayloadCode (subjectStr, "URL of last page visited: " + response.domain);
}
});
or, if you wanted it more like your case way for some reason, maybe this is the sorta thing you'd like...
if(location.hash) {
var locHashParts = location.hash.split('/');
if(locHashParts.length > 1 && locHashParts[0] == '#!newtopic') {
var subjectStr = '';
var bodyStr = '';
var request = {};
switch(locHashParts[1]) {
case 'opencomments-site-discussions':
request = {
url: true,
domain: true
}
break;
default:
break;
}
chrome.extension.sendMessage(request, function(response) {
console.debug('The url is "' + response.url + '" and the domain is"' + response.domain + '"');
if(repsone.url && response.domain) {
runPayloadCode(subjectStr, "URL of last page visited: " + response.domain);
}
});
}
}
}
listen
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
var response = {};
if(request.url) {
response.url = "someURL";
}
if(request.domain) {
response.domain = "someDomain";
}
sendResponse(response);
});
You can try the following code:
case 'opencomments-site-discussions':
chrome.extension.sendMessage({
name: "domain"
},
function (response) {
subjectStr = response.domain;
if(subjectStr){
chrome.extension.sendMessage({
name: "url"
},
function (response) {
bodyStr = "URL of last page visited: " + response.url;
if (bodyStr) {
runPayloadCode(subjectStr, bodyStr);
}
});
}
});
However, can't you merge both message's chrome.extension.sendMessage({name: "url"}) and chrome.extension.sendMessage({name: "domain"}) into single message(Because i see them independent) and eliminate multiple nesting?

Categories