My server is firing an event to client2 on some request by client1.The fired event is captured correctly by client2.
See the below code:
'experimentService.experimentPermissionChangedByOwner subscribe': function(eventName, event){
if(this.resource.id == event.eventData.resource) {
if (event.eventData.permissionType == "unshare") {
message = this.resource.name +" has been unshared by the owner: "+event.eventData.ownerUsername+". "+messagePart2;
this.openWorkspaceObject({id: event.eventData.dashboardId, namespace: "bjkbb", type: "jhvhhkk" });
}
else {
message = "Owner: "+event.eventData.ownerUsername+" changed permission of "+ this.resource.name +" to "+ event.eventData.permissionType +". ";
if (event.eventData.permissionType == "view") {
message += messagePart2;
}
this.publish("elements.atlas.resource-page-modified", this.resource);
}
this.openDialog({
dialogClass: elements.AlertCollaborators,
message: message
});
}
this.publish("event.ack", {eventId: event.id});
},
The above code is going to create a small dialog box with a message. Now the problem is on refreshing the browser, it again goes into the subscribe function. I dnt know how to handle this? Moroever after putting debug points I saw that it does not go into publish for this method. Then how does the subcribe capture it again??
Related
I am working on an Android app using cordova and implemented a push notification system using the cordova $PushPlugin.
My PushPlugin code (source):
module.run(function($rootScope,$cordovaPush) {
var androidConfig = {
"senderID": "replace_with_sender_id",
};
document.addEventListener("deviceready", function(){
$cordovaPush.register(androidConfig).then(function(result) {
// Success
}, function(err) {
// Error
})
$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);
});
On clicking the push notification received, I want to redirect the user to a specified page in my app. I referred this(based on phonegap pushplugin) but could not figure out a solution. Any help will be appreciated.
This is a simple solution without using any angular routes.
case 'message':
if (notification.foreground === false){
window.location = '#/abc';
window.location.reload();
}
If you check structure of object notification, you will see that there is an attribute foreground, which will be false when you come to app from clicking notification. You can use that to put your logic
case 'message':
if(notification.foreground === false){
//add logic for navigation to your specific page i.e $state.go('myPage')
}
I have a packaged chrome app having multiple windows. For example if I click a button in first window then a second window opened. Now how to send messages or commands to each other.
I have read a lot about it but did not figure out as i am very much new to this.
Any sample code will be very helpful.
There is a existing question How to communicate between multiple windows of the same chrome app?, but did not understand how to do it.
Thanks in advance!!!
You can use the postmessage method of a window, in order to send information to another window. By following this approach, you can execute a method from a window (A) on a different window (B). You'll need to create an event on window B that will inform A that the method ran correctly.
The code would be something like:
Sender:
//create popup window
var domain = 'http://scriptandstyle.com';
var myPopup = window.open(domain + '/windowPostMessageListener.html','myWindow');
//periodical message sender
setInterval(function(){
var message = 'Hello! The time is: ' + (new Date().getTime());
console.log('blog.local: sending message: ' + message);
myPopup.postMessage(message,domain); //send the message and target URI
},6000);
//listen to holla back
window.addEventListener('message',function(event) {
if(event.origin !== 'http://scriptandstyle.com') return;
console.log('received response: ',event.data);
},false);
Destination:
//respond to events
window.addEventListener('message',function(event) {
if(event.origin !== 'http://davidwalsh.name') return;
console.log('message received: ' + event.data,event);
event.source.postMessage('holla back youngin!',event.origin);
},false);
You can also find an in-dept explanation here: http://davidwalsh.name/window-postmessage
In the case of a Chrome app, the part about the domain is not required.
You need something as:
targetWindow = chrome.app.window.get("window-id").contentWindow;
targetWindow.postMessage(message, "*");
to send a message, while to receive:
window.addEventListener('message', function(event) {
var windowId = chrome.app.window.current().id;
console.log(windowId + ': received a message: ' + event.data, event);
var message = 'hello back!';
console.log(windowId + ': sending message: ' + message);
event.source.postMessage(message, event.origin);
});
I make three links on AJAX success function. I want a JavaScript function to run every time any of those links are clicked while user is on that page. I understand it is easy but I am unable to get the script run on every click. It just runs on clicking of first link and does nothing on clicking of other links. Here is the code:
request.success(function(data) {
//Put the heading on the div
//http://stackoverflow.com/questions/12898475/using-jquery-to-replace-text-inside-h3-header
var dataReceived = null;
$("#bookList h3 #spanId").text("A list appears");
for(var i=0;i<data.length;i++){
dataReceived =data[i].name;
$("#bookList").append("<a href id=bookLink>"+dataReceived+"</a>" +"<br>");
}
$("#bookLink").click(function(event){
$.getScript("information.js",function(){
dealWithData();
});
});
});
request.fail(function(jqXHR, status, errorMessage) {
if((errorMessage = $.trim(errorMessage)) === "") {
alert("An unspecified error occurred. Check the server error log for details.");
}
else {
alert("An error occurred: " + errorMessage);
}
});
dealWithData for now just has an alert:
function dealWithData(){
alert("Reached here");
}
Any help is appreciated. Thanks.
I don't like using .click() any more since it has been deprecated. You should also change it to use:
.on("click", function(event) {
I am doing pushnotification for both Android/IOS.
I have used a cordova push-plugin https://github.com/phonegap-build/PushPlugin, it seems to work great.
Info : I'm on a AngularJS project.
In my NotificationHelper factory i have this init method:
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};
I also defined those methods on mains.js :
var onNotificationGCM = function(event) {
// call back to web service in Angular.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var service = injector.get('NotificationHelper');
service.onNotificationGCM(event);
};
It's a trick to call angularJS factory from main javascript.
'onNotificationGCM' call the 'NotificationHelper.onNotificationGCM' method :
helper.onNotificationGCM = function(e) {
switch (e.event) {
case 'message':
// Notification happened while app was in the foreground
if (e.foreground) {
logger.debug('[notification] [message] Foreground : ' + JSON.stringify(e));
} else { // Notification touched in the notification tray
logger.debug('[notification] [message] Background : ' + JSON.stringify(e));
if (e.coldstart) {
// App was not running and user clicked on notification
} else {
// App was running and user clicked on notification
}
}
decriptPayloadNotification(e.payload);
break;
case 'registered':
logger.debug('[notification] [registered] : ' + JSON.stringify(e));
if (e.regid.length > 0) {
registerUser(e.regid, 'gcm');
}
break;
case 'error':
logger.debug('[notification] [error] : ' + JSON.stringify(e));
break;
default:
logger.debug('[notification] [default] : Unknown, an event was received and we do not know what it is : ' + JSON.stringify(e));
break;
}
};
During the first use, everything work good :
'Registered' event is received
Notifications are received
When i'm on foreground I receive 'message' event :
NotificationHelper: [notification] [message] Foreground : {"event":"message","from":"847593779913","message":"Agenêts 23/03 10h\r\n","collapse_key":"do_not_collapse","foreground":true,"payload":{"lt":"school","lv":"E1154","notId":"35429","title":"Agenêts le 23/03/2015","message":"Agenêts 23/03 10h\r\n"}}
When i'm on background, if i receive notif and touche it on notification tray, I receive 'message' event :
NotificationHelper: [notification] [message] Background : {"event":"message","from":"847593779913","message":"la piscine sera fermée 1 journée pour raison technique","coldstart":false,"collapse_key":"do_not_collapse","foreground":false,"payload":{"lt":"swimming pool","lv":"E114","notId":"29869","title":"23/04/2015 fermeture de la piscine","message":"la piscine sera fermée 1 journée pour raison technique"}}
BUT, if i kill my app, everything stop to work.
If i restart app, i will not receive anymore 'message'event and 'onNotificationGCM' will not be called.
I founded some articles speaking about this problem, but without success :
Stackoverflow : Phonegap PushNotification to open a specific app page
Does anyone has an idea about this problem ?
If you are using node-gcm as push notification server side I hope this might help for your question:
things to check:
use adb logcat from console and check your device logs to see if your device receives any notification (you should see some logs from gcmservices if you receive). I believe you should see some logs because otherwise you probably wouldn't get any notification when the app is on foreground either.
check if you add "title" and "message" keys on your message data (this draw me crazy before)
check if delayWhileIdle parameter is false
sample message variable and method i am using is below:
var pushAndroidSender = new gcm.Sender('Your GoogleApi Server Key Here');
var message = new gcm.Message({
collapseKey: 'demo',
delayWhileIdle: false,
timeToLive: 3,
data: {
"message":"What's up honey?",
"title":"Come on"
}
});
pushAndroidSender.send(message, registrationIds, function(err, result) {
if (err) {
console.error("this is an error: " + err);
} else {
console.log("this is a successful result:" + result);
}
});
I was asking myself why it worked correctly the first time and not the following times...and i had this idea :
maybe callback function is subscribed to plugin first time but not the next times.
And this is exactly the source of my problem. I call "pushNotification.register" only one time to init plugin and get ids...
But the next time I launch app, i don't instanciate again the plugin, so pushplugin don't know which method to call in callback request.
So answer is : Call "pushNotification.register" in each application launch !
In my code, i have to call method below on each "deviceready" event :
helper.init = function() {
// Instanciate push plugin notification
var pushNotification = window.plugins.pushNotification;
var errorHandler = function(error) {
logger.debug('errorHandler = ' + error);
};
if ($rootScope.isAndroid()) {
var senderId = CONFIG.NOTIFICATION_ANDROID_SENDER_ID;
pushNotification.register(function(result) {
logger.debug('successHandler = ' + result);
}, errorHandler, {
'senderID' : senderId,
'ecb' : 'onNotificationGCM'
});
}
};
I'm working on a chat app with Meteor and I'm assuming spam will be an issue so I want to incorporate a Captcha that pops up if you comment too quickly (like more than 3 times in 5 seconds). I have the javascript code below but I have no idea how to do this. Is it possible to have a Captcha just pop up somewhere on the screen? If so, does anybody know how to do this? Here is the code for the chat app part:
Javascript:
// render all of our messages in the ui
Template.chatBox.helpers({
"messages": function() {
return chatCollection.find();
}
});
// get the value for handlerbar helper user
Template.chatMessage.helpers({
"user": function() {
if(this.userId == 'me') {
return this.userId;
} else if(this.userId) {
getUsername(this.userId);
return Session.get('user-' + this.userId);
} else {
return 'anonymous-' + this.subscriptionId;
}
}
});
// when Send Chat clicked at the message to the collection
Template.chatBox.events({
"click #send": function() {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
},
"keypress #chat-message": function(e) {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
if (e.which == 13) {
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
console.log("you pressed enter");
e.preventDefault();
//repeat function from #send click event here
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
}
});
chatStream.on('chat', function(message) {
chatCollection.insert({
userId: this.userId,
subscriptionId: this.subscriptionId,
message: message
});
});
This sounds like a great idea, but there are some issues with using a 'conditional captcha'. One being that the JavaScript doesn't have any way to persist beyond a page reload besides cookies and localStorage. So a simple reload and clearing of the cookies would defeat it. Not to mention how to handle it on the server, which isn't sure whether it should be expecting a valid captcha input or not.
With that caveat out of the way, you could set a global variable that acts as a 'timer' and just keeps track of the lapse. So replace the last block with:
chatStream.on('chat', function(message) {
//do we already have a timer?
if(typeof window.chatTimer == 'undefined'){
//no, so start one right now
window.chatTimer = new Date().getTime();
}else{
//we already have a timer. Is it 5 seconds old?
var now = new Date().getTime();
if( now - window.chatTimer < 5000) {
alert('Not so fast, tiger.');
return false;
}else{
chatCollection.insert({
userId: this.userId,
subscriptionId: this.subscriptionId,
message: message
});
}
This example uses reCaptcha, minus the custom stuff you would pass in.
Perhaps this has changed recently, but Spambots don't run JavaScript. They are kinda like search engine crawlers that follow links and look for form and textbox elements, and then knit their poison into a POST request to the form's action attribute, bypassing any JavaScript that wants to block it.
In fact, one of the alternatives to a captcha is simply to dynamically generate a hidden input with JavaScript that has an obscure ID/name that the server is waiting for. Spambots won't run this JavaScript, so the checkbox never gets made, so the bot gets rejected without knowing why. Here's more on that.
I have added some code to your code. I never use Meteor so I don't know whether this code is work or not in Meteor. But is test this by creating similes project here
Template.chatBox.events({
"click #send": function() {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
//Validation
var bot =Check_bots();
if(bot==false)
{
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
// Do whatever you want when a Bot detected
}
},
"keypress #chat-message": function(e) {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
if (e.which == 13) {
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
console.log("you pressed enter");
e.preventDefault();
//repeat function from #send click event here
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
}
});
Here is the Validation Codes
<script type="text/javascript">
var lastintime=0;
var defference=0;
var msg_count=0;
function Check_bots()
{
var seconds = new Date().getTime() / 1000;
seconds=parseInt(seconds);
if(lastintime < seconds)
{
defference = seconds -lastintime;
lastintime=seconds;
if(defference<=5 && msg_count>=3)
{
return true;
}
else
{
return false;
}
}
}
</script>