To open external links within an application being developed with Ionic, use the Cordova InAppBrowser plugin that can be used to open images, access web pages, and open PDf files.
The plugin can be installed by the following command:
cordova plugin add cordova-plugin-inappbrowser
To install and configure the plugin in the application with ngCordova, more information here .
Example:
View code:
<ion-content ng-controller="ExampleController" padding="true">
<button class="button button-full button-assertive" ng-click="openInExternalBrowser()">
Browser do sistema
</button>
<button class="button button-full button-assertive" ng-click="openInAppBrowser()">
Nova instância inAppBrowser
</button>
<button class="button button-full button-assertive" ng-click="openCordovaWebView()">
Cordova Webview
</button>
</ion-content>
Controller code:
angular.module('starter', ['ionic'])
.controller("ExampleController", function ($scope) {
$scope.openInExternalBrowser = function()
{
window.open('http://google.com','_system','location=yes');
};
$scope.openInAppBrowser = function()
{
window.open('http://google.com','_blank');
};
$scope.openCordovaWebView = function()
{
window.open('http://google.com','_self');
};
});
Understanding better:
_blank: It opens the URL in inAppBrowser
_self: Open in Cordova WebView if the URL is in the white list, otherwise it opens in InAppBrowser.
_system: Opens in the system browser.
location = yes: Shows the full URL of the page in the InAppBrowser in an address bar, by default location
is set to no
.
Events:
This plugin has events combined with $rootScope
:
When you start to open the page:
$rootScope.$on('$cordovaInAppBrowser:loadstart', function(e, event));
Event called when the InAppBrowser starts opening the page.
When finished loading:
$rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event));
Event that fires after the browser has finished loading the page.
Error loading:
$rootScope.$on('$cordovaInAppBrowser:loaderror', function(e, event));
Event triggered when InAppBrowser encounters an error opening URL.
When you open the window:
$rootScope.$on('$cordovaInAppBrowser:exit', function(e, event));
Event triggered when the InAppBrowser window is closed.
Example with event loading page:
Injects a css and javascript into the loaded page
$rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event){
//insere um css por código
$cordovaInAppBrowser.insertCSS({
code: 'body {background-color:blue;}'
});
// insere um Javascript por arquivo
$cordovaInAppBrowser.executeScript({
file: 'script.js'
});
alert("Página carregada");
});