I'm trying to build a simple application on cordova using aerogear push notification plugin
What i'm doing is following closely this guide: https://aerogear.org/docs/guides/aerogear-cordova/AerogearCordovaPush/#_sample_example
However, after put the sample code in my js, this line:
push.register(onNotification, successHandler, errorHandler, pushConfig);
will cause a reference error since push is not defined
I followed all the step before and the aerogear-cordova-push plugin is in the folder of the plugins, maybe i require some additional steps to refer to the plugin?
Also, the plugin provide an index.html as example inside its folder, but even using that i'm not able to resolve push
I tried to move the js files of the plugin in the www folder and linked them on index before the execution of index.js, since this it isn't very correct cause other reference errors
The index.html on the www folder is the same that a standard cordova project provide after its creation
This is my index.js, i'm able to show the error on android throught the try catch:
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);
},
// 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() {
try {
app.receivedEvent('deviceready');
var pushConfig = {
pushServerURL: "...",
android: {
senderID: "...",
variantID: "...",
variantSecret: "..."
}
};
push.register(app.onNotification, successHandler, errorHandler, pushConfig);
}
catch (e){
alert(e);
}
function successHandler() {
console.log('success')
}
function errorHandler(message) {
console.log('error ' + message);
}
},
onNotification: function(event) {
alert(event.alert);
},
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);
}}; app.initialize();
I solved this because the plugin wasn't correct installed in my application, and the installation would fail because i was missing the google-service.json file that is required in order to build for android
Related
I am trying to implement cordova-plugin-email-composer.I installed the plugin using cli
cordova plugin add https://github.com/katzer/cordova-plugin-email-composer.git
I got an error Uncaught ReferenceError: require is not defined at email_composer.js:22.
In the link u can find the plugin. I added the code attached below in my index.js file. Can anyone help to solve this? Thankyou.
index.js:
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, function () {
cordova.plugins.email.isAvailable(
function (isAvailable) {
alert("is email mobile available? " + (isAvailable ? "Yes" : "No"));
if(isAvailable){
window.plugin.email.open({
to: 'anu.barbie143#gmail.com',
subject: 'Greetings',
body: 'How are you? Nice greetings from Leipzig'
}, callback, scope);
}
}
);
}, false);
function callback(){
console.log("callback function");
}
function scope(){
console.log("scope function");
}
},
email_composer.js:
var exec = require('cordova/exec'),
isAndroid = navigator.userAgent.toLowerCase().indexOf('android') > -1,
mailto = 'mailto:';
In the above code i got an error require is not defined.Can anyone help me to solve this?
Thankyou.
I made it work by doing following
cordova plugin rm cordova-plugin-email-composer
then add the plugin with version 0.8.2,by following command since there is an open error in plugin version 0.8.3 for loolipop
cordova plugin add https://github.com/katzer/cordova-plugin-email-composer.git#0.8.2
index.js
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');
cordova.plugins.email.open({
to: 'test#gmail.com',
cc: 'test#gmail.com',
bcc: [],
subject: 'Greetings',
body: 'How are you? Nice greetings from Naresh'
});
},
// 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);
}
};
app.initialize();
Hope it helps you..
I modified your code and its working now.
So please check it once.
cordova.plugins.email.isAvailable(function (isAvailable) {
// alert('Service is not available') unless isAvailable;
alert("is email mobile available? " + (isAvailable ? "Yes" : "No"));
if(isAvailable){
window.plugin.email.open({
to: 'test#test.com',
subject: 'Greetings',
body: 'How are you? Nice greetings from Leipzig',
}, function(){
console.log('email view dismissed');
},
this);
}
});
if alert is "no" it means you don't have any email application or configuration.
I am working on application in Nativescript which implements push notification. Lets say server sends push notification and based on action mentioned in payload of notification i will have to redirect in application. This redirection should be performed if user taps on notification from drawer and application is in background. Other case when application should not redirect if its in foreground. I have managed a flag for that as follow
app.js
application.on(application.launchEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.suspendEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.resumeEvent, function (args) {
appSettings.setBoolean('AppForground', true);
});
application.on(application.exitEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.lowMemoryEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
application.on(application.uncaughtErrorEvent, function (args) {
appSettings.setBoolean('AppForground', false);
});
And on Push notification listener
var settings = {
// Android settings
senderID: '1234567890', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(data, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
var payload = JSON.parse(JSON.parse(pushNotificationObject).data);
if (appSettings.getBoolean('AppForground') == false){
switch (payload.action) {
case "APPOINTMENT_DETAIL":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id
}
});
break;
case "MESSAGE":
frame.topmost().navigate({
moduleName: views.appointmentDetails,
context: {
id: payload.id,
from: "messages"
}
});
break;
case "REFERENCES":
frame.topmost().navigate({
moduleName: views.clientDetails,
context: {
id: payload.id,
name: ""
}
});
break;
default:
}
}
},
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
},
// Error Callback
function(error) {
alert(error);
}
);
Now the problem, is that if application is in killed state and notification arrives. Then it sets flag to true as application is launched which it should not. So due to that redirection is not performed and in other cases when application is in foreground state then also its navigating through pages (which should not be) on receiving notification.
I doubt about flag management is causing the problem but not sure. Would you please guide me if anything is wrong with what i did ?
UPDATE
I am using push-plugin.
Thanks.
I use this for notifications
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
This plugin use FCM, it adds to datas received from notifications foreground parameter so from payload you can determine if app was background(foreground==false, app is not active or was started after notification arrived) or foreground(foreground==true, app is open and active), but you need to some changes to code as they are different plugins
You can use pusher-nativescript npm module.
import { Pusher } from 'pusher-nativescript';
/*Observation using the above.
- Project gets build successfully.
- on run -> ERROR TypeError: pusher_nativescript__WEBPACK_IMPORTED_MODULE_6__.Pusher is not a constructor
- Use: import * as Pusher from 'pusher-nativescript';
- Make sure to install nativescript-websocket with this package.
*/
var pusher = new Pusher('Your_app_key', { cluster: 'your_cluster_name' });
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(JSON.stringify(data));
});
Trying to migrate to ionicPush but getting errors anyway I do it:
Option 1 - Angular method
When I put $ionicPush.init as per guide in the app.js or anywhere for that matter, getting:
Uncaught TypeError: $ionicPush.init is not a function
When I check $ionicPush it has 2 methods, register and unregister. So clearly it gets imported, but for whatever reason doesnt have .init
Top of app.js looks like this:
.run(function(AppRootService, $ionicPlatform, $ionicPush, $cordovaSplashscreen,$window, $timeout) {
$ionicPlatform.ready(function() {
$ionicPush.init({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
}
});
$ionicPush.register();
Option 2 - Regular JS way
Put this code in app.js after $ionicPlatform.ready()
var push = new Ionic.Push({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
}
});
push.register(function(token) {
console.log("Device token:",token.token);
});
Ionic.io();
Still nothing, this time error is Uncaught ReferenceError: Ionic is not defined
Ran both of these:
ionic add ionic-platform-web-client
ionic plugin add phonegap-plugin-push
Moved around Ionic.io(), not luck
I think you have to init io and activate debug/dev mode.
Here is the all steps...
ionic add ionic-platform-web-client
ionic plugin add phonegap-plugin-push
ionic io init
ionic config set dev_push true
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
var push = new Ionic.Push({
"debug": true
});
push.register(function(token) {
console.log("Device token:",token.token);
});
});
})
Checkout this page for setting up push for platforms (iOS, Android)
http://docs.ionic.io/docs/push-from-scratch
This is the code i use with the phonegap-plugin-push
inside the run phase
document.addEventListener("deviceready", function () {
var androidConfig = {
'senderID': '****google-project-id****',
'sound': true,
'vibrate': true
};
var Push = PushNotification.init({
"android": androidConfig
});
Push.on('registration', function(data) {
// device token:
var deviceToken = data.registrationId;
console.log('pushToken', deviceToken);
});
Push.on('error', function(e) {
console.error('Notifications error: ', e.message, e);
});
Push.on('notification', function(response){
console.log('norification', response)
console.log('any additinal data the push recieved', response.additionalData)
});
}, false);
try what i did and it will work for you.
I have been unable to successfully figure out why $.ajax refuses to connect to the Internet in Phonegap. The same code runs well in a standard HTML file. Access Origin is set to *.
Originally I thought Phonegap was refusing a connection to the Internet. However, it loads JQuery and JQuery Mobile remotely (by link tag). JQuery continues to return an error. Tested in JBoss Developer Studio (PG 4.1.2) and PG by commandline 4.3.
The error returned by stringifying the error object
error: {"readyStaate":4,"responseText":"{\n \"code\":
\"ENOTFOUND\",\n \"errno\":\"ENOTFOUND\",\n \"syscall\":\:getaddrinfo\"\n}","responseJSON":{"code":"ENOTFOUND","errno":"ENOTFOUND","syscall":"getaddrinfo"},"status":500,"statusText":"error"}
The Javscript used:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('load', this.onDeviceLoad, false);
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceLoad: function() {
window.isAndroid = navigator.userAgent.match(/(android)/gi) != null;
},
onlineEvent: function() {
},
offlineEvent: function() {
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
// online/offline must be set in onDeviceReady
document.addEventListener('online', this.onlineEvent , false);
document.addEventListener('offline', this.offlineEvent , false);
$.ajax({
method: "POST",
url: "http://www.someserver/server.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg.posts );
console.log('NETWORK' + msg.posts);
})
.fail(function(error) {
alert("error: " + JSON.stringify(error));
});
},
receivedEvent: function(id) {
}
};
app.initialize();
Edit: I am aware of what the 500 error is. I have tested the server. It works fine with HTML5 and the same JQuery AJAX call. My hunch is that there is something with Phonegap; between the JQuery Client call and the server that is causing the error.
Edit2: The server name is private. The string is set to a real server on my actual code.
jQuery doesn't "connect to the internet". It's just a JavaScript library. The 500-status response you're getting is telling you that the server you're trying to POST to is erroring:
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
I am trying to test the upload functionality using this guide with the only exception of using cfs-s3 package. This is very basic with simple code but I am getting an error on the client console - Error: Access denied. No allow validators set on restricted collection for method 'insert'. [403]
I get this error even though I have set the allow insert in every possible way.
Here is my client code:
// client/images.js
var imageStore = new FS.Store.S3("images");
Images = new FS.Collection("images", {
stores: [imageStore],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Images.deny({
insert: function(){
return false;
},
update: function(){
return false;
},
remove: function(){
return false;
},
download: function(){
return false;
}
});
Images.allow({
insert: function(){
return true;
},
update: function(){
return true;
},
remove: function(){
return true;
},
download: function(){
return true;
}
});
And there is a simple file input button on the homepage -
// client/home.js
'change .myFileInput': function(e, t) {
FS.Utility.eachFile(e, function(file) {
Images.insert(file, function (err, fileObj) {
if (err){
console.log(err) // --- THIS is the error
} else {
// handle success depending what you need to do
console.log("fileObj id: " + fileObj._id)
//Meteor.users.update(userId, {$set: imagesURL});
}
});
});
}
I have set the proper policies and everything on S3 but I don't think this error is related to S3 at all.
// server/images.js
var imageStore = new FS.Store.S3("images", {
accessKeyId: "xxxx",
secretAccessKey: "xxxx",
bucket: "www.mybucket.com"
});
Images = new FS.Collection("images", {
stores: [imageStore],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
I have also published and subscribed to the collections appropriately. I have been digging around for hours but can't seem to figure out what is happening.
EDIT: I just readded insecure package and everything now works. So basically, the problem is with allow/deny rules but I am actually doing it. I am not sure why it is not acknowledging the rules.
You need to define the FS.Collection's allow/deny rules in sever-only code. These are server-side rules applied to the underlying Mongo.Collection that FS.Collection creates.
The best approach is to export the AWS keys as the following environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, remove the accessKeyId and secretAccessKey options from the FS.Store, and then move the FS.Collection constructor calls to run on both the client and server. The convenience of using env vars is mentioned on the cfs:s3 page
In addition to this you can control the bucket name using Meteor.settings.public, which is handy when you want to use different buckets based on the environment.