i am trying to register the devuice fror push notification using the phonegap plugin. In the success action of the AJAX i call the registration action but its not alerting the registration ID. can anyone figure out it.
here the index.js
// Begin boilerplate code generated with Cordova project.
var app = {
// Application Constructor
initialize: function () {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
connectionStatus = navigator.onLine ? 'online' : 'offline';
if(connectionStatus !="online")
{
//$.mobile.changePage($("#seconddiv"));
window.location.replace("no-internet.html");
}
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function () {
},
setupPush: function() {
console.log('calling push init');
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx"
},
"ios": {
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
console.log('after init');
push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId);
var oldRegId = localStorage.getItem('registrationId');
if (oldRegId !== data.registrationId) {
// Save new registration ID
localStorage.setItem('registrationId', data.registrationId);
// Post registrationId to your app server as the value has changed
}
alert(localStorage.getItem('registrationId'));
var parentElement = document.getElementById('registration');
var listeningElement = parentElement.querySelector('.waiting');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
push.on('notification', function(data) {
console.log('notification event');
navigator.notification.alert(
data.message, // message
null, // callback
data.title, // title
'Ok' // buttonName
);
});
}
};
i call the app.setupPush(); inside the ajax success handler
here the signin.js
var KPSCtuts = KPSCtuts || {};
$("#btn-submit").click(function(){
var userName = $("#txt-username").val();
var password = $("#txt-password").val();
//alert(KPSCtuts.Settings.Url);
$("#loaderIcon").show();
$.ajax({
type: 'POST',
dataType: "json",
url: KPSCtuts.Settings.Url,
data:"username=" + userName + "&password=" + password + "&login=",
success: function (resp) {
if (resp.success === true) {
// Create session.
var today = new Date();
var expirationDate = new Date();
expirationDate.setTime(today.getTime() + KPSCtuts.Settings.sessionTimeoutInMSec);
KPSCtuts.Session.getInstance().set({
userProfileModel: resp.userProfileModel,
userId: resp.userId,
userName: resp.userName,
sessionId: resp.sessionId,
expirationDate: expirationDate,
keepSignedIn:$('#chck-rememberme').is(":checked")
});
app.setupPush();
// Go to main menu.
window.location.replace("index.html");
$("#loaderIcon").hide();
return;
} else {
if (resp.extras.msg) {
$("#ctn-err").html("<p>"+resp.extras.msg+"</p>");
$("#dlg-invalid-credentials").show();
$("#ctn-err").addClass("bi-ctn-err").slideDown();
$("#loaderIcon").hide();
}
}
},
error: function (e) {
//$.mobile.loading("hide");
//console.log(e.message);
// TODO: Use a friendlier error message below.
$("#ctn-err").html("<p>1-Oops! KPSCtuts had a problem and could not log you on. Please try again in a few minutes.</p>");
$("#ctn-err").addClass("bi-ctn-err").slideDown();
$("#loaderIcon").hide();
}
});
});
Try the registration code in onDeviceReady function.Registration ID will be same until you uninstall the app.
In HTML:
<body onload="onLoad()">
In Script:
function onLoad()
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx"
},
"ios": {
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId);
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
push.on('notification', function(data) {
console.log('notification event');
navigator.notification.alert(
data.message, // message
null, // callback
data.title, // title
'Ok' // buttonName
);
});
}
Related
i'm using cordova-plugin-local-notification and I want the notification to trigger on setReminder() function. Please how can I do this
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
document.getElementById("setreminder").addEventListener("click", setReminder);
cordova.plugins.notification.local.registerPermission(function (granted) {
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
StatusBar.overlaysWebView(false);
StatusBar.backgroundColorByHexString('#4281F5');
StatusBar.styleDefault();
document.getElementById("setreminder").addEventListener("click", setReminder);
var sound = "js/when.mp3";
var date = new Date();
function setReminder() {
cordova.plugins.notification.local.schedule({
id: 1,
title: "IKD-FAD",
message: "Your Bus Is Almost Here!",
at: date,
sound: sound,
icon: "js/citybus.png"
});
}
}
};
app.initialize();
document.addEventListener("deviceready", ondeviceready, false);
function ondeviceready() {
}
function setReminder(btn) {
navigator.vibrate(1000);
cordova.plugins.notification.local.schedule({
id: 1,
title: btn.dataset.name,
text: "Your Bus Will Be At The Station In " + changedTime + " Minutes",
trigger: { in: btn.dataset.diff, unit: 'minute' },
sound: "file://js/when.mp3",
icon: "file://img/mmArtboard.png"
});
This fixed it for me
I'm working with a react.js project and convert it into a mobile application, that part is ok, the idea is that the app must receive push notifications, once the user clicks the notification, it must change the react route, I've been trying this code but had not success the app doesn't change the route once the user clicks the notification, I had success getting the react-router instance, but i don't know how to use it properly to go to the desired route.
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
var mmjUser=localStorage.getItem("mmj-user");
if (mmjUser !== null) {
var push = PushNotification.init({
"android": {
"senderID": "491359499412",
"forceShow": 'true'
},
"ios": {
"alert": "true",
"badge": "true",
"sound": "true",
"senderID": "491359499412"},
"windows": {}
});
push.on('registration', function(data) {
console.log("registration event");
});
push.on('notification', function(data) {
console.log("notification event");
console.log(JSON.stringify(data));
var reactRouter=require('react-router');
reactRouter.HistoryLocation.replace('/waiting');
push.finish(function () {
console.log('finish successfully called');
});
});
push.on('error', function(e) {
console.log("push error");
});
}
}
};
app.initialize();
this is the reactRouter object that i'm getting
Thanks for your help!
I have a question about integration between mootools and socket.io on client :
Suppose :
- server application developed in node.js which have a socket.io listen
I want to define a class to manage connection with the server, client socket.io must reside inside this class.
Actually i'm able to send connection from this class but i'm not able to manage push event. How to correct this code ?
var Push = new Class({
Implements: [Events],
initialize : function() {
this.socketServer = '192.168.1.3';
this.listeningPort = '8080';
this.socketIoUrl = 'http://'.concat(this.socketServer,':', this.listeningPort);
//
this.socketIO = io.connect(this.socketIoUrl, {
'connect timeout' : 500,
'reconnect' : false,
'reconnection delay' : 0,
'reopen delay' : 500,
'max reconnection attempts' : 0
});
// Attach Socket.io events
this.attachEvents();
// Creating a socket.io room
this.socketIO.emit('create', this.filterName);
},
// SOCKET.IO EVENTS
attachEvents : function() {
socketIO.on = function(e) {
log.info('aaa');
socket.on('disconnect', function() {
log.error("SOCKET.IO CLIENT disconnected");
this.fireEvent("disconnect", [ e.data, e ]);
});
socket.on('connect_failed', function() {
log.error("SOCKET.IO connection failed ");
this.fireEvent("connect_failed", [ e.data, e ]);
});
socket.on('message', function() {
log.debug(e.data);
processMessage(e.data);
this.fireEvent("message", [ e.data, e ]);
});
}.bind(this)
return this
}
});
It seems that you've lost this context of your Push class instance.
To fix this problem you'll need to modify the attachEvents function like this:
// SOCKET.IO EVENTS
attachEvents : function() {
var self = this; // save context to variable called "self"
this.socketIO.on('disconnect', function() {
log.error("SOCKET.IO CLIENT disconnected");
self.fireEvent("disconnect", [ e.data, e ]);
});
this.socketIO.on('connect_failed', function() {
log.error("SOCKET.IO connection failed ");
self.fireEvent("connect_failed", [ e.data, e ]);
});
this.socketIO.on('message', function() {
log.debug(e.data);
processMessage(e.data);
self.fireEvent("message", [ e.data, e ]);
});
return this;
}
Now it works.
Socket.io init must be defined in a specific method invoked by initialize. Direct initializatioin in nitialize does not work :
initialize : function(filterName, instrumentCode, fieldList, bankName, userName) {
var self = this;
....
self.initConnection();
self.attachEvents();
},
initConnection : function() {
var self = this;
self.socketIO = io.connect(this.socketIoUrl, {
'connect timeout' : 500,
'reconnect' : true,
'reconnection delay' : 0,
'reopen delay' : 500,
'max reconnection attempts' : 0
});
logger.debug ('socket.io init');
},
attachEvents : function() {
var self = this;
// Attach Socket.io events
//this.attachEvents();
self.socketIO.on('disconnect', function() {
logger.error('Client disconnected');
self.initConnection();
self.resendRequest();
});
self.socketIO.on('connect_failed', function() {
logger.error('Connection failed');
self.initConnection();
self.resendRequest();
});
self.socketIO.on('message', function(data) {
self.processMessage(data);
});
self.socketIO.emit('create', this.filterName);
},
resendRequest : function() {
if (this.operationType == "SUBSCRIBE") {
subscribe();
} else {
unsubscribe();
}
},
Thanks to everyone.
I'd like to use Linkedin share functionality with my custom button, but the callback function won't be called on success, any idea?
This is my code:
var sh = IN.UI.Share().params(
{
url: "someUrl"
});
sh.success(function(){console.log('Linkedin share success')});
sh.place();
Created a mini-pen which you can view here https://codepen.io/craigiswayne/pen/Bqqbjz
Documentation on this subject can be found here: https://developer.linkedin.com/docs/share-on-linkedin
IN.Event.on(IN, 'systemReady', function() {
var shareLink = document.getElementById('shareLink');
shareLink.onclick = function(){
event.preventDefault();
var params = {
"comment": "Check out developer.linkedin.com! https://www.example.com",
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(params))
.result(function(xhrResult){
alert('success :)');
})
.error(function(errorObj){
alert('Error');
alert(errorObj.errorMessage);
});
};
});
i need a very simple login system for my web application with backbone.js
Workflow:
App Start -> LoginView -> When Logged In -> App
Here is my solution. What can i do better?
Login Status Model:
window.LoginStatus = Backbone.Model.extend({
defaults: {
loggedIn: false,
userId: null,
username: null,
error: "An Error Message!"
},
initialize: function () {
_.bindAll(this, 'getSession', 'setStorage');
},
getSession: function (username, password) {
var tmpThis = this;
$.getJSON('http://requestURL.de/getSession.php?username=' + username + '&password=' + password, function(data) {
if (data != null) {
tmpThis.setStorage(data.id, data.username);
$.mobile.changePage("#home");
}
});
},
setStorage: function(userId, username) {
localStorage.setItem("userId", userId);
localStorage.setItem("username", username);
this.set({ "loggedIn" : true});
}
});
Here is my Login View:
window.LoginView = Backbone.View.extend({
el: $("#login"),
initialize:function () {
this.render();
},
events: {
"click input[type=submit]": "onSubmit"
},
onSubmit: function(event) {
var username = $(this.el).find("#user-username").val(),
password = $(this.el).find("#user-password").val();
this.model.getSession(username, password);
return false;
},
render:function () {
if (this.model.get("loggedIn")) {
var template = _.template( $("#login_template").html(), {} );
} else {
var template = _.template( $("#login_template").html(), { "error" : this.model.get("error") } );
}
$(this.el).html( template );
}
});
My suggestion to you is making the login outside the backbone app and only after a success login process let them access the "single page app"
You can refer to this backbone project which does the login request using POST method. https://github.com/denysonique/backbone-login