Hybrid ionic mobile app: hide login screen after successful login - android

I am developing mobile app with ionic framework.it has a side menu with following links
1.Home
1.Login
2.About
3.Settings
When user is logged in i want to change the login in side menu to myprofile link
In the login controller
.controller('LoginCtrl',function($scope,$http,$ionicPopup,$state){
$scope.login=function(user){
//http call for login api
//set the auth token
window.localStorage.setItem('usertoken',response.token);
$state.go('app.profile');
}
}})
In Menu controller
.controller('MenuCtrl', function($scope, $ionicModal, $timeout) {
//shows the login link when the user is not logged in othewise show profile.
if(window.localStorage.getItem('usertoken')==null){
$scope.showloginlink=true;
$scope.showprofilelink=false;
}else{
$scope.showloginlink=false;
$scope.showprofilelink=true;
}
});
Here is htmll
<ion-list >
<ion-item menu-close href="#/app/login" ng-show="showloginlink">
Login
</ion-item>
<ion-item menu-close href="#/app/profile" ng-show="showprofilelink">
Profile
</ion-item>
The problem it dosen't show the profile link after login,but when i refresh the entire page it will works as i expected
How to solve this problem?
UPDATE
I have solved the problem via reload the state
$state.go('app.profile',null,{reload: true});
But i wil get another error,side menu is missing from my user_profilepage
I've added this enable-menu-with-back-views="true" in menu.html ,but still i have the menu missing problem:(
Note:I am using ionic tabs template

Try wrapping your assignment with $apply, like this:
$scope.$apply(function() {
if(window.localStorage.getItem('usertoken')==null){
$scope.showloginlink=true;
$scope.showprofilelink=false;
}else{
$scope.showloginlink=false;
$scope.showprofilelink=true;
}
});
If you get an error to say a digest is already running, swap out $scope.$apply with $timeout, which is a service you'll need to inject. That will defer the update until the next digest if you don't specify a specific delay.
So first inject it into your controller by adding it as a parameter:
.controller('LoginCtrl',function($scope,$http,$ionicPopup,$state, $timeout){
Then, replace $scope.$apply from the previous listing:
$timeout(function() {
if(window.localStorage.getItem('usertoken')==null){
$scope.showloginlink=true;
$scope.showprofilelink=false;
}else{
$scope.showloginlink=false;
$scope.showprofilelink=true;
}
});

Related

how to implement parental gate in nativescript

I've created an app that uses a set of embed videos of YouTube.
Since this is made for kids, my app after 6 years got removed because I did not implement parental gateway when kids might accidentally click on the YouTube logo - it will load the YouTube app and continue there.
i'm trying to understand how, in general, I can grab such event, that is fired when something ( click ) wants to open another app ( not just youtube ) - and then activate my page that I've created as a parental gateway - and if the answer is correct - then I continue.
EDIT: Was able to do so far:
I found event that might help suspendEvent
I'm able to catch it and forward to my page
[stuck] unable to catch the event the loads the native app
DOES NOT WORK: Things that doesn't work so far:
(1) suspendEvent, the event is fired when the native app loads - but cannot prevent/disable/control the native app lunch for a "parental gate" in the middle ( youtube app still loaded and in the background - parental gate page is switched )
import { on as applicationOn } from "tns-core-modules/application";
...
applicationOn(suspendEvent, this.activateParentalGateway, this);
(2) WebViewExt
it has an event called WebViewExt.shouldOverrideUrlLoadingEvent, but I'm unable to load the YouTube plugin inside it
<WebViewExt debugMode="true" (loaded)="onWebViewLoaded($event)">
<YoutubePlayer id="player" [src]="settings.player.src"></YoutubePlayer>
</WebViewExt>
webview.on(WebViewExt.shouldOverrideUrlLoadingEvent, (args1: ShouldOverrideUrlLoadEventData) => {
console.log("shouldOverrideUrlLoadingEvent firing for url : ", args1.url);
utils.openUrl(args1.url);
});
is there a native replacement for shouldOverrideUrlLoadingEvent ?
I want to share my solution for now, I've seen tons of posts related to parental gate which non were answered.
Not sure if Google Play will accept it, but was able to set a parental gate in my app, please share your answers as well if you find something better !
So I'm using this pkg: https://github.com/Notalib/nativescript-webview-ext, which is a webview component (browser) and my code looks like this
player.component.html
<GridLayout class="page page-content" xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:nota="#nota/nativescript-webview-ext">
... other html code ...
<nota:WebViewExt (loaded)="onWebViewLoaded($event)"
src='https://www.youtube.com/embed/{{ src }}'
width="100%" height="100%">
</nota:WebViewExt>
</GridLayout>
player.component.ts
import { Component, OnInit, NgZone } from "#angular/core";
import { RouterExtensions } from "nativescript-angular/router";
import { WebView } from "tns-core-modules/ui/web-view";
import { WebViewExt, ShouldOverrideUrlLoadEventData } from "#nota/nativescript-webview-ext";
/*
Events
*/
onWebViewLoaded(args) {
let webview: WebView = args.object;
// This code will grab any click that try to load/switch to an external app/url
webview.on(WebViewExt.shouldOverrideUrlLoadingEvent, (_args: ShouldOverrideUrlLoadEventData) => {
// Disable the event
_args.cancel = true;
// Switch to parental gateway
this.activateParentalGateway(_args.url);
});
}
activateParentalGateway(blocked_url) {
if (typeof(blocked_url) !== "string") {
return false;
}
// run inside the ngZone to connect the event back to the
// component state ( otherwise there's no "this" variable )
this.zone.run(() => {
this.routerExtensions.navigate(['parental_gateway', blocked_url], {
transition: {
name: "fade"
}
});
});
}
parental_gateway.component.html
This is where we ask some "grownup" question ... for now just made two buttons for testing correct / wrong answers.
<GridLayout columns="*" rows="*">
<StackLayout row="0" width="100%" orientation="horizontal">
<Label text="Answer this question please" width="20%" height="50"></Label>
<Button text="Correct" (tap)="answeredCorrect($event)"></Button>
<Button text="Failed" (tap)="answeredWrong($event)"></Button>
</StackLayout>
</GridLayout>
parental_gateway.component.ts
import { RouterExtensions } from "nativescript-angular/router";
import { openUrl } from "tns-core-modules/utils/utils";
answeredCorrect() {
console.log("Answer was correct");
// openUrl will actually open the YouTube video
// in a native app ( basically continue the event )
openUrl(this.blocked_url);
// In the background we want to go back from the
// parental gate page that we've been in
// and switch to the video where we first clicked it.
this.routerExtensions.backToPreviousPage();
}
answeredWrong() {
console.log("Wrong answer go back");
// Just go back to our page where we've clicked the link
this.routerExtensions.backToPreviousPage();
}
Hope this helps others, if so, please vote up.

Ionic InAppBrowser on Android doesn't navigate to custom Url Scheme

I am having a setup, where I open a url in the plugin InAppBrowser with target '_blank'. The plugin Deeplinks is also installed and configured.
const browser: InAppBrowserObject = this.iab.create(url, '_blank', <InAppBrowserOptions>{
location: "no",
toolbar: "no",
footer: "no"
});
browser.on('loadstart').subscribe((event: InAppBrowserEvent) => {
console.log(event);
if (event.url.indexOf('wflwr://payment/success') > -1) {
browser.close();
}
if (event.url.indexOf('wflwr://payment/cancel') > -1) {
browser.close();
}
if (event.url.indexOf('wflwr://payment/error') > -1) {
browser.close();
}
});
I shortened it to show just the important parts. The url which is opened is https://www.voan.ch/wfl/ (it is just a Mock before the real implementation)
The expected behaviour is, that on a click on each of the links on the url, the browser instance inside the app should close. This works as intended on iOS, but not on Android. The event is just not triggered. If I change one of the urls to e.g. CANCEL, then the Event gets triggered.
the support for this was added in latest pr
to use it you will need 2 things:
for example to allow whatsapp custom scheme and twitter
add new config.xml preference with the custom schemes you want to support:
<preference name="AllowedSchemes" value="whatsapp,twitter" />`
add event listeners customscheme:
inAppBrowserRef.addEventListener('customscheme', function (event) {
//do whatever you want here like:
window.open(event.url, "_system");
});

Detect first time user for meteor app

I am building an app with Meteor and I am looking to create a first time user launch screen- something like an "About/Welcome" page. Essentially, something that would pull a one-time screen after launching the app for the first time and never appear again; if the user has already opened the app they would be directed to another page.
I am not using login credentials, so I need a different solution than checking to see if the user is logged in or not.
How would I go about configuring this? I have tried searching all over the web and can't seem to find a solution for this. Please note this is different from a "Launch Screen".
You will need to either use localstorage, or set a cookie.
I'd suggest trying localstorage first. There are several packages on atmosphere that should help,
Using the frozeman:storage package (meteorpad example):
Template.body.helpers({
beenHereBefore: function() {
var beenHereBefore = LocalStore.get('BeenHereBefore', {reactive: false});
console.log(LocalStore.get('BeenHereBefore', {reactive: false}));
if (beenHereBefore !== true){
LocalStore.set('BeenHereBefore', true, {reactive: false})
console.log(LocalStore.get('BeenHereBefore', {reactive: false}));
}
return beenHereBefore;
},
});
<body>
{{#unless beenHereBefore}}
<h1> Welcome first time visitor! </h1>
{{else}}
<div class="outer">
<div class="logo"></div>
<h1 class="title">Leaderboard</h1>
<div class="subtitle">Select a scientist to give them points</div>
{{> leaderboard}}
</div>
{{/unless}}
</body>
Just some simple JavaScript should do the trick:
if (Boolean(localStorage.getItem('visitedApp'))) {
// user's been here before
} else {
// do stuff for first time user
localStorage.setItem('visitedApp', true);
}

Handle Android Back Button on Phonegap InAppBrowser

I would like to disable or override the Android Back button while I am navigating pages on the InAppBrowser. Can I add an event listener that can handle that?
EDIT:
Looking at the answer by #T_D below the solutions provided are the closest I could get to. It does not seem to be possible to override the button in InAppBrowser as all the PhoneGap tweaks stop working while navigating pages on this plugin. I was not able to find any other solution rather than modifying the API library. If there are any PhoneGap guys here and know something more, I 'll be glad to get some comment. Thanks.
The closest I got:
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener("backbutton", function () { })
According to the documentation the behaviour of the hardware back button can be configured now for the InAppBrowser:
hardwareback: set to yes to use the hardware back button to navigate backwards through the InAppBrowser's history. If there is no previous page, the InAppBrowser will close. The default value is yes, so you must set it to no if you want the back button to simply close the InAppBrowser.
Thanks to Kris Erickson.
So just update your InAppBrowser plugin if the backward navigation is the desired behaviour.
For more details see: https://github.com/apache/cordova-plugin-inappbrowser/pull/86
You can do it quite easily now (as of InAppBrowser version 0.3.3), but you will have to edit the Java files. Go to src/com/org/apache/corodova/inappbrowser directory and edit the InAppBrowserDialog.java:
Change
public void onBackPressed () {
if (this.inAppBrowser == null) {
this.dismiss();
} else {
// better to go through the in inAppBrowser
// because it does a clean up
this.inAppBrowser.closeDialog();
}
}
to
public void onBackPressed () {
if (this.inAppBrowser == null) {
this.dismiss();
} else {
if (this.inAppBrowser.canGoBack()) {
this.inAppBrowser.goBack();
} else {
this.inAppBrowser.closeDialog();
}
}
}
Then go to InAppBrowser and find the goBack function, change:
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
private void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
to
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
And now the hardware back button will go back until there are no more backs to do. I really think this should be the default behavior in android since the Done button already closes the InAppBrowser window.
This worked for me in PhoneGap 2.7, help came from here, How do I disable Android Back button on one page and change to exit button on every other page
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.addEventListener("backbutton", function (e) {
e.preventDefault();
}, false );
}
I was having this same issue and finally got it to work, I'll post the answer here in case it helps someone.
This is the code I use:
window.new_window = window.open(url, '_blank', 'location=no');
window.new_window.addEventListener("exit", function () {
window.new_window.close();
});
So the key basically is to attach the exit event, which gets called when the back button of the device is tapped.
BTW, I used cordova.js, and build my apps locally using the Cordova CLI, I don't know if that makes any difference, I mention it just in case.
EDIT NOTE: As far as I know, it's not possible to override the back-button for the InAppBrowser in PhoneGap. But I did my best searching for possible solutions...
There's an eventListener to override back-button in PhoneGap -doesn't work for InAppBrowser-
function onDeviceReady(){
document.addEventListener("backbutton", onBackKeyDown, false);
}
Alternative eventListener to override back-button -the OP said this didn't work either-
var ref = window.open('http://www.stackoverflow.com', '_blank', 'location=yes');
ref.addEventListener("backbutton", function () {
//logic here
})
Overriding the Back-button in an Activity -this is plain java, obviously didn't work in PhoneGap-
#Override
public void onBackPressed()
{
//logic here
}
Conclusion:
Above solutions didn't work, following links (this answer, this one and a third one) didn't help either. So it's highly possible that overriding the back-button for the InAppBrowser in PhoneGap is not possible. If someone does come up with a solution or if things changed for a new PhoneGap version feel free to let us know...
EDIT:
Installing this plugin may take you to closest solution:
cordova plugin add org.apache.cordova.inappbrowse
What this plugin will do, in WP8, it will overlay back/forward/close button on InAppBrowser whenever you open any link/page in it.
See this image:
Use jQuery mobile:
$(document).on('backbutton',
function(e){
e.preventDefault();
// YOUR CODE GOES HERE
});
Running Cordova 5.1.1 and when i load pages in the inappbroswer i like having the back button work until the inappbrowser exits back to my index.html page because it's blank and just sits there. So i used the following code to fix this. It exits the app when it exits the inappbrowser.
window.open = cordova.InAppBrowser.open;
var ref = window.open(url, '_blank', 'location=no');
ref.addEventListener('exit', function () {
navigator.app.exitApp();
});
As far as I know it's not possible to override or detect the back button from inAppBrowser. When you press the back button, inAppBrowser will hide and return control to the Phonegap page. You can catch this with the focus event on the window, (using jQuery) like
var browser = window.open('http://example.com', '_blank', 'location=no');
$(window).on('focus', function() {
browser.show();
});
to reopen the browser. You could then use browser.executeScript() to signal the webapp loaded in the browser, if you like.
Inspired by this forum post.
I know this question has an answer already but I post my answer for those who any of these answers didn't work for them(such as myself):
so I have a multi page app for android and IOS and I am using cordova 5.x and I added the code below in every page except the page I needed InAppBrowser:
delete window.open;
and then for the rest of the pages I used:
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(event) {
// your code for handling back button comes here
}
for handling back button
note that: delete window.open; base on the documentation
manually restore the default behaviour of 'window.open'
after that InAppBrowser plugin worked great and I handled back button in all pages correctly.
one last thing don't forget to add:<script type="text/javascript" charset="utf-8" src="cordova.js"></script> in pages you need to have InAppBrowser.
hope this help.

phonegap android GO button to not submit form

I'm writing an app with Phonegap and I have a register form that is sent through ajax. It works fine when you hit the register button and execute the formcheck() function. However, when I hit the GO button from my android phone it submits the form instead of going through the formcheck() process. I tried:
<form id="RegForm" onsubmit="formcheck();return false;">
My form has no proper submit button but a button like this:
<input type="button" id="submitbtn" onclick="formcheck()"/>
I also tried to create a new OnSubmitForm() function that calls the formcheck() one but with no avail. Thank you for helping.
Found it!
1) Add this to the JS section:
$(document).ready(function() {
$("#YourFormName").submit(function() {
FormCheck();
return false;
});
});
function FormCheck() {
... validation process here ...
}
2) Make sure to include a Submit button in your form .. ( <input type="submit" )
Hope it'll help others so my 5 hour trying & testing time won't go wasted :)
Simply ensure your form tag is:
<form type='submit' onsubmit='return false;'></form>
This makes the submit action not do anything.
If you also need to hide the keyboard refer to How can I hide the Android keyboard using JavaScript?. A simple onsubmit='hideKeyboard(); return false;' will take care of this.

Categories

Resources