Ionic application open link in system browser - angularjs

I want to open the link in the system browser, for example in ios in safari and for android chrome(whatever the default browser is).
The problem i'm having the that the link does indeed opens in the system browser but it also open in the application. I want the link only to open in the system browser and not inside the app.
this is my code.
<a ng-href="http://example.com/login/{{user._id}}" onclick="window.open(this.href, '_system', 'location=yes')" class="ion-home color-primary item"> Dashboard</a>
Keep in mind that im also passing an id to my endpoint.

try
<a class="ion-home color-primary item" href="#" onclick="window.open('http://example.com/login/{{user._id}}', '_system', 'location=yes'); return false;"> Dashboard</a>

In newer(3.0) version In App Browser Plugin is better solution.
<button ion-button block clear (click)="openWebpage(url)">Open Webpage</button>
and the openWebpage method goes like this
openWebpage(url: string) {
const options: InAppBrowserOptions = {
zoom: 'no'
}
// Opening a URL and returning an InAppBrowserObject
const browser = this.inAppBrowser.create(url, '_self', options);
// Inject scripts, css and more with browser.X
}

You can do it with InAppBrowser plugin https://cordova.apache.org/docs/en/3.0.0/cordova/inappbrowser/inappbrowser.html
If you for some reason don't want to use plugin, check out my answer on similar question: https://stackoverflow.com/a/30397786/1630623
EDIT: if you are already using the plugin, you might have to either remove the onclick code and add target="_system", or add event.preventDefault(); in the onclick handler

Capacitor has an easy to use plugin for launching an in-app browser.
https://capacitorjs.com/docs/apis/browser
Installation:
npm install #capacitor/browser
npx cap sync
Usage:
import { Browser } from '#capacitor/browser';
const openCapacitorSite = async () => {
await Browser.open({ url: 'http://capacitorjs.com/' });
};

Simple Solution
<a href="#" onclick="window.open('https://www.badhaobusiness.in',
'_system', 'location=yes'); return false;"> www.badhaobusiness.in</a>

Use this method in ActionSheet to open link in another browser:
import { ActionSheetController} from '#ionic/angular';
...
constructor(public actionSheet: ActionSheetController) {}
async presentActionSheet() {
const action = await this.actionSheet.create({
buttons: [{
text: 'Open link',
icon: 'link-outline'
handler: () => {
window.open('http://google.com');
}
}]
});
await action.present();
}
}

Related

How to logout in react

I'm trying to logout using this method:
In render I have a div like this:
<div>
<a href="#" onClick={this.logout()}>LOGOUT</a>
</div>
and the logout function:
logout() {
// localStorage.clear();
location.href = 'localhost:3000';
}
At localhost:3000 I have the login page.
Put when I press logout, nothing happends. What can I do?
Thank you
this solved my problem
logout() {
localStorage.clear();
window.location.href = '/';
}
Give to us the Minimal Example to be tested.
You already checked if your function is being called? Try to put some console.log inside logout(), it smells Binding to methods of React class issue.
Try to insert http:// inside location.href, like this: location.href = 'http://localhost:3000';

How to add a custom error page in Cordova InAppBrowser or hide the error url?

pleas check this attached image I'm building an Ionic Android app with the InAppBrowser plugin. When the internet connection is not available, the plugin shows web page not available and requesting url.
Please help me customise the InAppBrowser error page (404 page). Or help me hide the requesting url.
Thank you.
I think I misunderstood your problem, first time, sorry about that. I'm reading again your problem and I'm figuring out what's happening. You need to add a custom configuration at config.xml to redirect to an error page when Cordova detect it. I hope this solve your problem.
<preference name="ErrorUrl" value="myErrorPage.html"/>
The original response works when you want to open a link through Cordova inAppBrowser plugin. If this doesn't sort out your problem, please reformulate your question.
Original response
You could be listening inAppBrowser events to figure what's happening.
Here, you can see how listen browser events, such as loaderror and manage the 404 error as you want. You must save a reference to inAppBrowser when open method is called, and then you could listen for error event.
function loadErrorCallBack(params) {
// Do stuff
}
inAppBrowserRef = cordova.InAppBrowser.open(url, target, options);
inAppBrowserRef.addEventListener('loaderror', loadErrorCallBack);
I am using Ionic 4 and I couldn’t manage to make the solution based on config.xml editing to work :
preference name="ErrorUrl" value="myErrorPage.html"/
Placing an addEventListener on loaderror didn’t work neither. It looks like it is not triggered by http errors and the plugin need a fix.
But we found a hack that is much simpler.
On loadstop we wait 500 milliseconds and then we get the loaded url by triggering executeScript with and window.location.href
If the loaded url is of the custom error page, in Cordova (not in IAB) we display a custom message with a back button.
It's a hack but that cover the requirement for now
I just came across the same problem and here's what I did. The code is for Android and works on IOS as well. But you would want to remove navigator.app.exitApp(); for IOS as Apple does not allow apps to take exit without pressing the home button.
Let me know if this works for you. It will hide default error page and open your custom error page. Write your own error code in myerrorpage.html
document.getElementById("openBrowser").addEventListener("click", openBrowser);
document.addEventListener("offline", onOffline, false);
function onOffline(e) {
e.preventDefault();
var src = 'myErrorPage.html';
var target = '_blank';
var option = "loaction=no, toolbar=no, zoom=no, hidden=yes, hardwareback=no";
var ref = cordova.InAppBrowser.open(src, target, option);
alert('Your device is Offline. Please check your connection and try again.');
navigator.app.exitApp();
}
function openBrowser() {
var url = 'https://www.yourlink.com';
var target = '_self';
var options = "location=no,toolbar=no,zoom=no, hardwareback=no, hidden=yes" ;
var ref = cordova.InAppBrowser.open(url, target, options);
}
When the components do not work, I perform the following procedure
ionic state reset
ionic platform remove android
ionic platform remove ios
ionic platform add android
ionic platform add ios
and try with ionicPlatform ready
<button class="button button-balanced" ng-click="OpenBrowser()">Test</button>
In controller
$scope.OpenBrowser = undefined;
$ionicPlatform.ready(function () {
$scope.OpenBrowser = function () {
$cordovaInAppBrowser.open('http://ngcordova.com', '_blank', options)
.then(function (event) {
})
.catch(function (event) {
$scope.Error = event;
});
};
});
I couldn't manage solution with setting ErrorUrl in Ionic 4 on Android to work.
Finally I came up with another solution - hide default error page and redirect user to any page (I use last page from event.url).
constructor(private iab: InAppBrowser) {
}
private openUrl(url: string)
{
this.platform.ready().then(() => {
if (this.platform.is('cordova')) {
this.openBrowser(url);
}
});
}
private openBrowser(url: string): InAppBrowserObject
{
const options: InAppBrowserOptions = {
location: 'no',
zoom: 'no',
hidden: 'no'
};
const browser = this.iab.create(url, '_blank', options);
browser.on('loaderror').subscribe(
event => this.onLoadError(event, browser)
);
return browser;
}
private onLoadError(event: InAppBrowserEvent, browser: InAppBrowserObject): void
{
browser.executeScript({
code: `
window.addEventListener('DOMContentLoaded', function () {
document.querySelector('body').style.background = 'black';
document.querySelector('body').innerHTML = '';
}, true);
window.addEventListener('load', function () {
window.location.replace('${event.url}');
}, true);
`,
}
).then();
}
Changing background and redirecting is tricky - from my experiments using injectCss won't work, because body is generated in the meantime. Using DOMContentLoader makes it black and clears text on screen.
But redirecting won't work in DOMContentLoader (don't ask me why), so you need to use load event.
It works great when user is using hardware back and returns to POST request - this way he will be redirected to GET of the same url (but you can use any url you want).

Firebase $authWithOAuthRedirect doesn't call $onAuth without page refresh

I have a simple Firebase Facebook OAuth login set like below by following the official tutorial for the Ionic Firebase Facebook login.
The problem is that once I click on the login with Facebook button, I get redirected to Facebook, I log in, and I get redirected back to my app. However, the problem is that I stay in the login page. Strange thing is that if I physically refresh my browser (testing with ionic serve) by pressing F5 the onAuth triggers and I get redirected to the Items page. If I don't refresh the browser, onAuth doesn't get called.
Did someone have this issue? How did you solve it?
Please note that yes, I did my research (and am slightly starting to lose it), but can't get it to work. I searched SO, tried with $timeout from google groups, tried to call $scope.$apply(), but all to no avail - so please help me figure out where I'm doing it wrong?
.controller('AppCtrl', function($scope, Items, Auth, $state, $ionicHistory) {
$scope.login = function(provider) {
Auth.$authWithOAuthRedirect(provider).then(function(authData) {
}).catch(function(error) {
if (error.code === "TRANSPORT_UNAVAILABLE") {
Auth.$authWithOAuthPopup(provider).then(function(authData) {
});
} else {
console.log(error);
}
});
};
$scope.logout = function() {
Auth.$unauth();
$scope.authData = null;
$window.location.reload(true);
};
Auth.$onAuth(function(authData) {
if (authData === null) {
console.log("Not logged in yet");
$state.go('app.login');
} else {
console.log("Logged in as", authData.uid);
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('app.items');
}
$scope.authData = authData; // This will display the user's name in our view
});
})
<ion-view view-title="Members area">
<ion-content padding="true">
<div ng-if="!authData">
<button class="button button-positive button-block" ng-click="login('facebook')">Log In with Facebook</button>
</div>
<div ng-if="authData.facebook">
<div class="card">
<div class="item item-text-wrap">Hello {{authData.facebook.displayName}}!</div>
</div>
<button class="button button-assertive button-block" ng-click="logout()">Log out</button>
</div>
</ion-content>
</ion-view>
edit: I sort of solved it by using $timeout:
$timeout(function(){
Auth.$onAuth(function(authData) {
if (authData === null) {
console.log("Not logged in yet");
$state.go('app.login');
} else {
console.log("Logged in as", authData.uid);
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('app.items');
}
$scope.authData = authData; // This will display the user's name in our view
});
}, 3000);
However, this just feels wrong (mildly put), and there has to be a better way, so please suggest one. Also, I noticed that the whopping 3second delay is barely enough (few of the resources I found suggested 500ms would be enough, but in my case, that's not the case).
Posted on the github issues, but will reply here as well.
This only happens in the browser using $authWithOAuthRedirect. The example was intended for cordova apps, so this really shouldn't be an issue.
But if you really need it, you could just skip the redirect and use a popup.
Auth.$authWithOAuthPopup(authMethod).then(function(authData) {
console.dir(authData);
});
This was a bug that has been fixed in the latest Firebase JS client release (2.3.0). You can now use $authWithOAuthRedirect and the $onAuth callback will be triggered when you navigate back to the page.

Cordova inAppBrowser plugin issue in ios and blackberry

I am developing cordova application for BB10,android,iod,windows8.
within that i have requirement of opening url in default device browser.
for that i had used org.apache.cordova.inappbrowser plugin.
but after using that i came across problem of relaunching application once i back from browser.
[problem in all platform except windows8]
so that i had used below solution,
jQuery(document).delegate('.external', 'click', function(e) {
window.open(e.target.href, '_system', 'location=yes');
e.preventDefault();
});
<a class="external" href="myUrl">Track Now</a>
with above solution,
Android: it was working fine.
Blackberry10 problem: Url is not opened in external browser it is only opened in app browser,
IOS Problem: url is not working at all(when i click on link nothing happened).
So, any help from your side is really appreciated.
Yeah below is the solution for my case.
And its working fine in all android, BlackBerry10 and IOS platform.
resolving blackberry issue by adding blackberry invoke plugin.
function openBlackBerryBrowser(url) {
function onInvokeSuccess() {
alert("Invocation successful!");
}
function onInvokeError(error) {
alert("Invocation failed, error: " + error);
}
blackberry.invoke.invoke({
target: "sys.browser",
uri: url
}, onInvokeSuccess, onInvokeError);
}
if (window.device.platform.toLowerCase().indexOf('blackberry') > -1) {
jQuery(document).delegate('.external', 'click', function(e) {
openBlackBerryBrowser(e.target.href);
});
} else {
jQuery(document).delegate('.external', 'click', function(e) {
e.preventDefault();
var ref = window.open(e.target.href, '_system', 'location=yes');
});
}
Hope this will help someone.
In my opinion is not necessary the use of jquery to do this. You could try something like this, but I tested only on Android and iOS:
In your controller:
$scope.openLink = function(url){
window.open(url, '_system');
};
html:
www.google.com
Let me know if works also on BB!

Sencha with phonegap Native open external link

I have deployed a native app android + ios with sencha touch + phonegap.
If we click a link inside the app it opens inside the app and we cannot go out.
Does someone now how it is posible to let links open into the phone browser?
window.open("yoururl", '_blank');
The phonegap version I used was 2.9.0 if I am not mistaken.
I had the same problem and solved it as follows:
Embed the JQuery javascript file in your project. In my case it was:
<script type="text/javascript" charset="utf-8" src="js/jquery-1.10.2.min.js"></script>
Then I wrote the following function, which I called in the onDeviceReady function:
function enableHttpLinks() {
$('.externalLink').click(function(e) {
e.preventDefault();
url = $(this).attr("href");
window.open(url, '_system');
});
}
In order for this function to work, you have a assign the class externalLink to all the links you want to open in the device browser, as shown below:
your link title
good luck...
Just add this function inside "launch" function, in the app.js like this:
launch: function() {
// Destroy the #appLoadingIndicator element
//Ext.fly('appLoadingIndicator').destroy();
// Initialize the main view
Ext.Viewport.add(Ext.create('yourApp.view.Main'));
// Voila :
Ext.Viewport.element.dom.addEventListener('click', function (e) {
if (e.target.tagName !== 'A') {
return;
};
var url = e.target.getAttribute('href');
var containsHttp = new RegExp('http\\b');
//if href value begins with 'http'
if(containsHttp.test(url)) {
e.preventDefault();
window.open(url, "_system"); // For iOS
navigator.app.loadUrl(url, {openExternal: true}); //For Android
}
else {
return;
}
}, false);
}, //...
Then you can build for android and iOS at the same time.

Resources