Search code examples
cordovaionic-frameworkionic4install-referrer

How to use Google Play Install Referrer API in Ionic?


I have been struggling over the past week figuring out how to use Google Play Install Referrer API, in an Ionic app. I have tried using the following approaches:

Approach 1: InstallBroadcast

I installed a cordova plugin called cordova-plugin-installreferrer and a npm module install-referrer. When I try to build the app in development mode, I get the response as empty array. But when I build it in production mode, I get plugin_not_found error. (PS: I have added it to the providers in the app.module.ts)

import { InstallReferrer } from 'install-referrer/ngx';
...
constructor(
  private installReferrer: InstallReferrer
) {
  this.installReferrer.getReferrer().then(data => {
      alert(JSON.stringify(data));
  }).catch((err) => {
      alert(JSON.stringify(err));
  });
}

I also realized the InstallBroadcast is deprecated now. We have to switch to Play Install Referrer API.

Approach 2: Play Install Referrer API

I tried installing a cordova plugin called cordova-install-referrer-api. And tried the following code:

declare var referrer: any;
...
initializeApp() {
  try{
    referrer.get().then((referrer) => {
      alert(JSON.stringify(referrer));
    });
  }catch(err){
    alert(err);
  }
...

Getting the following error: ReferenceError: referrer is not defined

Please help me get the referrer correctly, also let me know if I'm doing something wrong.


Solution

  • In your Approach 2: You've declared a variable referrer but I can't see the initialization in your code and the error you're getting is also not defined. So, I think you've not defined it.

    Remove the declared variable and replace your code with this:

    cordova.plugins.referrer.get().then((referrer) => {
        console.log(referrer);
        // Remove these comments, just an example from the original API
        // Result:
        // {
        //     clickTimestamp: 0,
        //     installBeginTimestamp: 0,
        //     referrer: "utm_source=google-play&utm_medium=organic"
        // } 
    
    }).catch((error) => {
    }); 
    

    And check if it works. The code is referenced from the Official Repo.