issue(InAppBrowser) Invalid event target

Hi Guys,

I’m having trouble subscribing to the events fired by the InAppBrowser. Opening a url in the browser is working fine, trying to subscribe to an event throws the error. I started a new project with a single page and only the inappbrowser plugin, still throws the same error.

I’ve been at this for days now. Am I doing something wrong, or is this a bug?

Full error

Runtime Error
Uncaught (in promise): TypeError: Invalid event target TypeError: Invalid event target at Function.FromEventObservable.setupSubscription
(localhost:8101/build/main.js:110502:19) at FromEventObservable._subscribe
(localhost:8101/build/main.js:110524:29) at FromEventObservable.Observable._trySubscribe (localhost:8101/build/main.js:18388:25) at FromEventObservable.Observable.subscribe
(localhost:8101/build/main.js:18376:27) at
localhost:8101/build/main.js:55640:49 at t.invoke
(localhost:8101/build/polyfills.js:3:11562) at Object.onInvoke
(localhost:8101/build/main.js:4403:37) at t.invoke
(localhost:8101/build/polyfills.js:3:11502) at n.run
(localhost:8101/build/polyfills.js:3:6468) at http: //localhost:8101/build/polyfills.js:3:3767 at t.invokeTask
(localhost:8101/build/polyfills.js:3:12256) at Object.onInvokeTask
(localhost:8101/build/main.js:4394:37) at t.invokeTask
(localhost:8101/build/polyfills.js:3:12177) at n.runTask
(localhost:8101/build/polyfills.js:3:7153) at a
(localhost:8101/build/polyfills.js:3:2312)

Version info

Ionic Framework: 3.1.1
Ionic App Scripts: 1.3.6
Angular Core: 4.0.2
Angular Compiler CLI: 4.0.2
Node: 6.9.3

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { InAppBrowser } from '@ionic-native/in-app-browser';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    InAppBrowser,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { Platform } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, private iab: InAppBrowser, private platform: Platform) {
    platform.ready().then(() => {
      const browser = this.iab.create('https://ionic.io');
      const watch = browser.on('loadstart').subscribe(function(event){
        console.log('loadstart');
      });
    });
  }
}

package.json

{
  "name": "ionic-hello-world",
  "version": "0.0.0",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.0.2",
    "@angular/compiler": "4.0.2",
    "@angular/compiler-cli": "4.0.2",
    "@angular/core": "4.0.2",
    "@angular/forms": "4.0.2",
    "@angular/http": "4.0.2",
    "@angular/platform-browser": "4.0.2",
    "@angular/platform-browser-dynamic": "4.0.2",
    "@ionic-native/core": "^3.6.1",
    "@ionic-native/in-app-browser": "^3.6.1",
    "@ionic-native/splash-screen": "3.4.2",
    "@ionic-native/status-bar": "3.4.2",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.1.1",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "^0.8.5"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.6",
    "typescript": "~2.2.1"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [
    "ios",
    {
      "platform": "ios",
      "version": "",
      "locator": "ios"
    }
  ],
  "description": "iabTest: An Ionic project"
}

See the Cordova plugin README:
https://github.com/apache/cordova-plugin-inappbrowser#browser-quirks-1

Edit: Okay, forget this - this only applies to the “browser” platform I think.

Yeah, that only applies to the browser. Thanks for your response though @Sujan12!

I’m pretty sure I’m doing everything as described in the Ionic native docs. Did I miss something? Is something missing in the docs? Or did I stumble upon a bug here?

I don’t know the code well enough to rate this.

If you have the time, try to implement the Cordova plugin directly (without Ionic Native, maybe it’S faster to do it on a plain Cordova starter project even without any Ionic) and see if the events work there. If it does, we know that either your Ionic Native code or the Ionic Native implementation are broken. (You did have a look at the open Github issues of Ionic Native, right?)

Thanks, I’ll try to implement the Cordova plugin directly.

I have been over the Ionic Native issues @ Github. Posted the issue there too: https://github.com/driftyco/ionic-native/issues/1446

Also, I’m not the only one having this issue: InAppBrowser Events+Communication

In case anyone else comes across this thread; any help, input or descriptions of similar issues are deeply appreciated.

1 Like

(I referenced this topic in the Github issue and other forum thread.)

Would be great if we could figure this out.

Implemented the plain cordova plugin using cordova.InAppBrowser and .addEventListener. Works like a charm.

So, how do we go about fixing this? Is there anyone we can ask to read along that created the Ionic Native wrapper for InAppBrowser, for instance?

  • First step: Share your working code with us.
  • Second step: We try to figure out what is wrong with the Ionic Native inAppBrowser plugin
  • Third step: We fix it and submit a PR.

Here is the raw code of the plugin:
https://github.com/driftyco/ionic-native/blob/master/src/%40ionic-native/plugins/in-app-browser/index.ts

Later maybe. Right now we both and the rest of the forum people should be enough to get a start on this.

One thing I noticed:
There is not real example on how to use on() in the docs. Maybe your code is somehow broken?

So I went through the other Ionic Native plugins to find out if there are similar implementations:

The one we are looking at:

Similar-ish:


Different:




Unfortunately both of the “similar-ish” plugins also don’t provide documentation on how to use on(). So this is not too much help :confused:

Ok, here’s the code I used for implementing the plain cordova plugin. I only changed home.ts. The rest is the same as in my original post. I commented the stuff I changed.

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { Platform } from 'ionic-angular';

// Declaring cordova so we can use it for the plugin
declare var cordova: any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, private iab: InAppBrowser, private platform: Platform) {
    platform.ready().then(() => {
      // If we run this in the browser without this if statement we get an error
      if (typeof cordova !== 'undefined') {
        // Open the InAppBrowser Cordova plugin
        const browser = cordova.InAppBrowser.open('https://ionic.io');
        // Add the event listener to the InAppBrowser instance
        browser.addEventListener('loadstart', function(){
          console.log('loadstart!');
        });
      }
    });
  }
}

Exactly. So I went for an online searching spree (for days) and the code in my original post is the version I came across the most in threads and examples. I tried all variants I found though, and all of them produced the same Invalid event target error. There being no example in the docs is the whole reason I’m here I guess. I’m posting these threads as a last resort, to find someone who can tell me how to write this or tell me I found a bug.

Thank you very much for your help so far Jan, you’re awesome. So, what’s next?

Good question.

The one thing I noticed in the code is that it says Observable<InAppBrowserEvent> instead of Observable<any> with (almost) all the other instances we looked at. Maybe change your local file to read <any> and try again?

(Problem is I don’t actually know enough about Observable or this code in general to really understand and fix it)

Oh and most of them have an annotation/decorator like @CordovaInstance or @InstanceCheck before them - but I have absolutely no idea what these do and how they work.

The following works fine for me in Android:

loginFacebook(): Promise<any> {
  return new Promise((resolve, reject) => {
    if (this.platform.is('cordova')) {
      var browserRef = this.inAppBrowser
        .create(`https://www.facebook.com/v2.9/dialog/oauth?client_id=${CLIENT_ID}&redirect_uri=${BASE_URL}/callback&response_type=token&scope=email`, "_blank", "location=no,clearsessioncache=yes,clearcache=yes");

      const exitSubscription: Subscription = browserRef.on("exit").subscribe((event) => {
        console.error("The Facebook sign in flow was canceled");
        reject(new Error("The Facebook sign in flow was canceled"));
      });

      browserRef.on("loadstart").subscribe((event) => {
        console.log(event);
        if ((event.url).indexOf(`${BASE_URL}/callback`) === 0) {
          console.log(event.url);
          exitSubscription.unsubscribe();
          browserRef.close();
          var responseParameters = ((event.url).split("#")[1]).split("&");
          var parsedResponse = {};
          for (var i = 0; i < responseParameters.length; i++) {
            parsedResponse[responseParameters[i].split("=")[0]] = responseParameters[i].split("=")[1];
          }
          if (parsedResponse["access_token"] !== undefined && parsedResponse["access_token"] !== null) {
            console.log(parsedResponse);
            resolve(parsedResponse);
          } else {
            console.error("Problem authenticating with Facebook");
            reject(new Error("Problem authenticating with Facebook"));
          }
        }
      });
    } else {
      console.error("loadstart events are not being fired in browser.");
      reject(new Error("loadstart events are not being fired in browser."));
    }
  });
}

Obviously it doesn’t work in Browser because of this: https://github.com/apache/cordova-plugin-inappbrowser#browser-quirks-1

@bash88 What platform did you test this on?

I am getting the same Invalid event target error.
Here is my code.

import { Component } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { InAppBrowser } from ‘@ionic-native/in-app-browser’;

@Component({
selector: ‘page-my’,
templateUrl: ‘my.html’
})
export class MyPage {

constructor(private iab: InAppBrowser, private platform: Platform) {
platform.ready().then(() => {

  let browser = this.iab.create(url, '_blank', 'location=no,toolbar=no');
  browser.show();
  browser.on("loadstart")
         .subscribe(
             (event) => {
                            console.log('Inappbrowser Loadstart Working', event);
                        },
                        err => {
                            console.log('InAppBrowser Loadstart Event Error: ' + err);
                        });
});

}
}

Did you find any working solution?

The problem is still there? No fix, I think.

Still not working

Here my code

this._browser = this.inAppBrowser.create('http://www.google.com', "_blank", "location=no,clearsessioncache=yes,clearcache=yes");

this._browser.on("loadstart").subscribe((resp) => {
  let alert1 = this._alertCtrl.create({
    subTitle: 'load start',
    buttons: ['ok!']
  });
  alert1.present();  
},err => {
    let alert1 = this._alertCtrl.create({
    subTitle: 'InAppBrowser Loadstart Event Error: ' + err,
    buttons: ['ok!']
  });
  alert1.present();  
});

Which version you using, Sir?