Ionic + Firebase + Custom-URL-scheme deep-linking
One slightly lacking feature in Firebase, is a strong user verification/ token workflow. There is a built in method for reseting passwords, but it is limited to the email template and syntax provided by Firebase. Also, when you create a user in Firebase, it only creates a user in FB dashboard, but doesn’t create them in your Firebase ref itself. By using Custom-URL-scheme, I can add other deep-linking features like custom promo codes, and user tokens to emails sent to users.
Custom URL scheme, provides an alternative method of accessing the app via a URL, but it also comes with its own challenges.
First of all, when you install the plugin, you need to create a schema (url) from which you can access your app. For example, in the below terminal command, you set a variable for the url you want to use to access the app from a link:
cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=mycoolapp
Once you’ve installed the plugin you can simply open safari on your emulator and type in : mycoolapp:// into the browser and it will prompt you to open your app.
The next problem is dealing with receiving the URL that you’ve opened the app with and parsing it get more information.
In Ionic, the main method of doing this is using a built in global function called : handleOpenURL(url).
Basically by defining the function at the top of your app.js, it will be triggered whenever the app is accessed from an external URL, and it will be able to access the URL:
function handleOpenURL(url) {
console.log(‘testing controller function’, url);
};So the next problem that I ran into with Ionic, is that I was getting the URL, but I was unable to manipulate it directly because the function has to be added globally and it can’t be directly put in any controller, and I was never sure what controller was currently active. The workaround for this, is to use angular.element, to get $rootScope from the document body, and run a function from $rootScope passing in the received URL as a parameter. So inside of handleOpenURL get the $rootScope:
var root = angular.element(body)
.scope();
root.reportAppLaunched(url);
Once you call the function the best place to ensure the function is run, is inside of the app.run method, and you can pass the URL data to a variable which can be received and parsed in another controller using $watch:
.run(function($ionicPlatform,
$rootScope,
$timeout,
$state) {
$ionicPlatform.ready(function() {
$rootScope.reportAppLaunched = function(url) {
$timeout(function() {
console.log(‘I am in the reportAppLaunched’);
$rootScope.token = url.split(‘/’)
.pop();
});So inside of the other controller I run:
$scope.$watch(function() {
return $rootScope.token;
}, setToken);And as soon as the url is received inside of the controller, I can manipulate it at will.