Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly retrieve redirection url on callback from capacitor browser in ionic app

I am trying to use ionic capacitor browser plugin for oauth flow but the browser return an empty object instead of the expected token or code string from the auth server.

I have tried using a custom urlscheme. The expected result is that the plugin should return an object url which should contain the 'code' but nothing is returned

    async openPage(){
        App.addListener('appUrlOpen', (data) => {
        console.log('Data: '+JSON.stringify(data));
        })
        await Browser.open({url: myUrl})

        this.addRedirectListener();
     }

    private async addRedirectListener() {
       App.addListener('appUrlOpen', async (data: any) => {
       console.debug('AppComponent - constructor - appUrlOpen');
       if(data.url.indexOf('callback#')!=-1) {
       let regEx = /(callback#access_token=)(.*)/g;
       let code = regEx.exec(data.url)[2];
       console.log(code);
       }
      await Browser.close();
      });
  }

Return an empty object instead of the expected object which should have been a token or code string. I have tried using the app plugin to track an event when the redirect uri is triggered.

I expect to return an object with token or code string but returns an empty object

like image 892
Joseph Adu Avatar asked Jun 27 '19 15:06

Joseph Adu


1 Answers

Using Cordova Plugins and Ionic Native

I've used cordova inAppBrowser Plugin with capacitor. working absolutely fine. we can use some of cordova plugin along with capacitor

Please read this

https://capacitorjs.com/docs/v2/cordova/using-cordova-plugins

Step 1 : Install cordova inappbrowser plugin with capacitor

npm install cordova-plugin-inappbrowser
npm install @ionic-native/in-app-browser
ionic cap sync
npm install --save @ionic-native/core

Step 2: Import Modules file on app.module.ts and add it in providers

Step 3: Use this demo code

async openBrowser() {
const options: InAppBrowserOptions = {
  location: 'no',
  clearcache: 'yes',
  zoom: 'yes',
  toolbar: 'yes',
  closebuttoncaption: 'close'
};
const browser = this.iab.create('https://google.com', '_blank', options);
console.log('opended');
console.log('browser=>');
this.util.errorToast('Opened');
browser.on('loadstop').subscribe(event => {
  console.log('event?;>11', event);
  this.util.errorToast(event.url);
  const navUrl = event.url;
  console.log(navUrl.includes('facebook'), navUrl.includes('instagram'));
  if (navUrl.includes('facebook') || navUrl.includes('instagram') || navUrl.includes('checkout')) {
    console.log('close');
    this.util.errorToast('Closed ddddd');
    browser.close();
  }
});
console.log('browser=> end');

}

like image 95
Rahul Jograna Avatar answered Oct 23 '22 00:10

Rahul Jograna