I have a problem! I am developing a phonegap application for both iOS and Android. when i call
window.open(url, "_system")
on iOS it opens up but i can navigate to the place i was before in my app. but when i open a link in android and navigate back to the app it starts from the start.
how can make the app stay the way it is when im leaving and return to it afterwards?
Andorid
function openInApp(link){
console.log("Open Call"+ link);
if(link.length<=1){
navigator.notification.alert(
'Page not found..!', // message
null, // callback
'Title', // title
'Ok' // buttonName
);
}else{
var ref = window.open(encodeURI(link), '_blank', 'location=yes');
ref.addEventListener('loaderror', function(event) {
navigator.notification.alert(
'error: ' + event.message, // message
null, // callback
'Title', // title
'Ok' // buttonName
);
});
}
}
IOS
function openInApp(link){
console.log("Open Call"+ link);
if(link.length<=1){
navigator.notification.alert(
'Page not found..!', // message
null, // callback
'Title', // title
'Ok' // buttonName
);
}else{
var ref = window.open(encodeURI(link), '_blank', 'location=no');
ref.addEventListener('loaderror', function(event) {
navigator.notification.alert(
'error: ' + event.message, // message
null, // callback
'Title', // title
'Ok' // buttonName
);
});
}
}
Would have asked this in a comment, but one needs 50 reputation for that … :(
In your config.xml do you have exit-on-suspend enabled? That is to say, do you have below <preference> element?
<cordova>
...
<preference name="exit-on-suspend" value="true" />
...
</cordova>
Related
I intend to get users geolocation even when the app sits dormant in the background and store the same in the database.
I'm using katzer's Cordova Background Plug-in,
When I try to access navigator.geolocation.getCurrentPosition inside backgroundMode.onactivate function, nothing happens, Whereas when I try passing hard coded values api is called, data is stored in database.
following is my code
document.addEventListener('deviceready', function() {
// Android customization
cordova.plugins.backgroundMode.setDefaults({
text: 'Doing heavy tasks.'
});
// Enable background mode
cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function() {
console.log('inside background')
a();
}
var a = function() {
console.log('a called')
navigator.geolocation.getCurrentPosition(function(pos) {
console.log('inside navigate');
var data = {
Lati: '123456',
Longi: '132456',
//LoginID: JSON.parse(window.localStorage.getItem('LoginId'))
EmpCode: localStorage.getItem('LoginId')
};
$http.post("https://app.sbismart.com/bo/ContactManagerApi/UpdateEmployeeLoc", data).success(function(rsdata, status) {
console.log('inside rsdata');
console.log(data.Lati + "," + data.Longi);
})
}, function(error) {
alert('Unable to get location: ' + error.message);
});
}
}, false);
cordova.plugins.backgroundMode.onfailure = function(errorCode) {
console.log(errorCode)
};`
and check as to why is it failing....then again u need to run the locationService function in a timeout function in the background to get updated about the location and check the location from previously got location.
Something like this...
cordova.plugins.backgroundMode.onactivate = function () {
setTimeout(function () {
a();
}, 5000);
}
Hope this helps.
I'm using the InAppBrowser plugin (v1.1.1) with Cordova for an OAuth login process. Unfortunately, the InAppBrowser doesn't appear to be closing the browser. My "closeBrowser" function instead continually triggers the interval, and the browser remains on-screen on the Android (I have not tried other devices at this time.)
Is there a way to forcibly close the InAppBrowser other than .close(), or hide it? Or maybe there's a flaw in my code somewhere that is locking the browser.
LogInPage.prototype.handleExternalLogin = function (externalLogin) {
var _this = this;
var ref = window.open(Environment_1.settings.baseUrl + externalLogin.route.url, "_blank", "location=no");
ref.addEventListener('loadstart', function (event) {
if (_.startsWith(event.url, Environment_1.settings.baseUrl + "/api/Account/account/ExternalLoginCallback")) {
// Now we want to load a different url that will give us the mobile access token
console.log('get external-mobile-token');
_this.closeBrowser(ref);
var ref2 = window.open(Environment_1.settings.baseUrl + "/api/Account/external-mobile-token", "_blank" /*, "location=no"*/);
ref2.addEventListener('loadstop', function (event) {
console.log('loadstop ' + event.url);
if (event.url == Environment_1.settings.baseUrl + "/api/Account/external-mobile-token") {
ref2.executeScript({ code: 'window.document.documentElement.innerText' }, function (contents) {
_this.login(contents);
_this.closeBrowser(ref2);
});
}
});
ref2.addEventListener('loaderror', function (event) {
console.log(event);
_this.closeBrowser(ref2);
// TODO - do something?
});
}
});
ref.addEventListener('loaderror', function (event) {
console.log(event);
_this.closeBrowser(ref);
// TODO - do something?
});
};
LogInPage.prototype.closeBrowser = function (browser) {
var interval = setInterval(function () {
console.log('closing');
browser.close();
}, 10);
browser.addEventListener('exit', function () {
console.log('closed');
clearInterval(interval);
});
};
LogInPage.prototype.login = function (token) {
console.log(token);
};
The above code is actually generated from TypeScript, but I figured I wouldn't confuse the issue.
It appears that closing an InAppBrowser and opening another at the same time was causing the issue; rewriting the process to only need one window solved my issue.
I am trying to implement push notification in ionic app for Android.
I have followed step by step guide from http://docs.ionic.io/v1.0/docs/push-from-scratch.
When I am running my app on android phone, then the registered users are listed in apps.ionic.io. So user registration is working fine.
But device registration is not working.
It is giving error Cannot read property 'pushNotification' of undefined
This is my code at the top of app.js
angular.module('starter', ['ionic','ngCordova',
'ionic.service.core',
'ionic.service.push',
'starter.controllers',
'starter.services'])
.config(['$ionicAppProvider', function($ionicAppProvider) {
// Identify app
$ionicAppProvider.identify({
// The App ID (from apps.ionic.io) for the server
app_id: '',
// The public API key all services will use for this app
api_key: '',
// Set the app to use development pushes
// dev_push: true
gcm_id: ''
});
}])
Here is the code in of my controller
.controller('DashboardCtrl', function($scope,$localstorage, WildfireService, CommonUtilityService,PushNotificationService,$ionicPopup, $ionicLoading) {
PushNotificationService.identifyUser();
PushNotificationService.pushRegister();
})
Here is my services.js
.service('PushNotificationService', function($q, $ionicUser, $ionicPush) {
var PushNotificationService = this;
PushNotificationService.identifyUser = function(){
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Add some metadata to your user object.
angular.extend(user, {
name: 'Technews',
bio: 'Hardcoded for now'
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
//alert('Identified user ' + user.name + '\n ID ' + user.user_id);
return true;
});
},
PushNotificationService.pushRegister = function(){
// Register with the Ionic Push service. All parameters are optional.
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
alert(notification);
return true;
}
});
}
})
Can any one tell me where is the error or what I am missing?
I have added these in index.html
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="lib/ionic-service-core/ionic-core.js"></script>
<script src="lib/ionic-service-push/ionic-push.js"></script>
Finally push notification is working for me. I moved the function call of pushRegister from controller to identifyUser function. So here is the new working code for me.
Controller code
.controller('DashboardCtrl', function($scope,$localstorage, WildfireService, CommonUtilityService,PushNotificationService,$ionicPopup, $ionicLoading) {
PushNotificationService.identifyUser();
})
Here is new services.js
.service('PushNotificationService', function($q, $ionicUser, $ionicPush) {
var PushNotificationService = this;
PushNotificationService.identifyUser = function(){
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Add some metadata to your user object.
angular.extend(user, {
name: 'Technews',
bio: 'Hardcoded for now'
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
//alert('Identified user ' + user.name + '\n ID ' + user.user_id);
PushNotificationService.pushRegister();
return true;
});
},
PushNotificationService.pushRegister = function(){
// Register with the Ionic Push service. All parameters are optional.
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
alert(notification);
return true;
}
});
}
})
I don't know about this new Ionic push notifications. I succesfully implemented push notifications in my Ionic App with ngCordova's push plugin for both Android an iOS (http://ngcordova.com/docs/plugins/pushNotifications/) just by following the examples there. The key is to put the code in the .run module in app.js.
Here is the code:
angular.module('notPush', ['ionic','notPush.controllers','notPush.factorys','ngCordova','ionic.service.core'])
.run(function($ionicPlatform, $rootScope, $http, $cordovaPush) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
// Manejador de notificaciones push para Android
if (ionic.Platform.isAndroid()){
var androidConfig = {
"senderID": "94XXXXXXXXXX", // ID HERE
"ecb": "window.casosPush"
};
try{
var pushNotification = window.plugins.pushNotification;
} catch (ex){
}
// Llamada en caso de exito
var successfn = function(result){
alert("Success: " + result);
};
// Llamada en caso de error
var errorfn = function(result){
window.alert("Error: " + result);
};
// Llamada de casos de notificacion push
window.casosPush = function(notification){
switch (notification.event){
case 'registered':
if (notification.regid.length > 0){
alert('registration ID = ' + notification.regid);
}
break;
case 'message':
alert(JSON.stringify([notification]));
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
};
try{
// Llamada de registro con la plataforma GCM
pushNotification.register(successfn,errorfn,androidConfig);
} catch(notification){
}
}
})
Just remember to install the plugin with
cordova plugin add https://github.com/phonegap-build/PushPlugin.git
I copied my code from the following link. It's a workaround for Passing Data From an InAppBrowser back to the app.
blogs.telerik.com/appbuilder/posts/13-12-23/cross-window-communication-with-cordova's-inappbrowser
The problem is that after each executescript() the Keyboard disappears.
This issue status here is "won't fix". So I'm wondering if there is an alternative solution. I only see a reference to KitKat users, but that would only represent a limited amount.
https://issues.apache.org/jira/browse/CB-5449
Suggestions?
setName: function() {
var win = window.open( "http://jsfiddle.net/tj_vantoll/K2yqc/show", "_blank",
"EnableViewPortScale=yes" );
win.addEventListener( "loadstop", function() {
win.executeScript({ code: "localStorage.setItem( 'name', '' );" });
var loop = setInterval(function() {
win.executeScript(
{
code: "localStorage.getItem( 'name' )"
},
function( values ) {
var name = values[ 0 ];
if ( name ) {
clearInterval( loop );
win.close();
$( "h1" ).html( "Welcome " + name + "!" );
}
}
);
});
});
}
Depending on your use case, it might be a feasible workaround to check if the keyboard is currently visible and avoid calling executeScript in that case.
Try using the com.ionic.keyboard plugin to get cordova.plugins.Keyboard.isVisible and use that in your setInterval function.
Hi guys i am working on drag and drop event in android via jquery mobile. I tested the code on browser works fine but not on device. can anybody help me out this issue. I am following 1st tutorial of the link....
http://www.elated.com/articles/drag-and-drop-with-jquery-your-essential-guide/
The problem can be one of the followings:
1- the device has to have internet connection
2- the files you used are not "jquery mobile". they are just jquery files that are used to develop web pages.
3- If you use the application on a tablet, I guess your application can work by the mouse of tablet. However it can't work by touching.
These are the problems that I can guess. I hope you find the exact solution. And if you find it, please post it here for me :)
This is my script i have done Emrullah...
<script type="text/javascript">
$(document).ready(function() {
$( init );
function init() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
$(function(){
$(".drag")
.bind( "dragstart", function( event ){
// ref the "dragged" element, make a copy
var $drag = $( this ), $proxy = $drag.clone();
// modify the "dragged" source element
$drag.addClass("outline");
// insert and return the "proxy" element
return $proxy.appendTo( document.body ).addClass("ghost");
})
.bind( "drag", function( event ){
// update the "proxy" element position
$( event.dragProxy ).css({
left: event.offsetX,
top: event.offsetY
});
})
.bind( "dragend", function( event ){
// remove the "proxy" element
$( event.dragProxy ).fadeOut( "normal", function(){
$( this ).remove();
});
// if there is no drop AND the target was previously dropped
if ( !event.dropTarget && $(this).parent().is(".drop") ){
// output details of the action
$('#log').append('<div>Removed <b>'+ this.title +'</b> from <b>'+
this.parentNode.title +'</b></div>');
// put it in it's original <div>
$('#nodrop').append( this );
}
// restore to a normal state
$( this ).removeClass("outline");
});
$('.drop')
.bind( "dropstart", function( event ){
// don't drop in itself
if ( this == event.dragTarget.parentNode ) return false;
// activate the "drop" target element
$( this ).addClass("active");
})
.bind( "drop", function( event ){
// if there was a drop, move some data...
$( this ).append( event.dragTarget );
// output details of the action...
$('#log').append('<div>Dropped <b>'+ event.dragTarget.title +'</b> into <b>'+
this.title +'</b></div>');
})
.bind( "dropend", function( event ){
// deactivate the "drop" target element
$( this ).removeClass("active");
});
});
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type="mousemove"; break;
case "touchend": type="mouseup"; break;
default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
return;
}
});
</script>
Your code looks fine and you told that it had worked on browser successfully. I think the problem is possibly the jquery file that you used. If you had linked the jquery file that resides on a web site, make sure your device has internet connection. If no internet connection, download and put the "jquery mobile" file into the assest/www folder and link the file.
Didn't you run the application on an emulator? What is the error you faced?