Can't close inAppBrowser on loadStop

I want to close the inAppBrowser window once a certain url has finished loading. User finishes survey.
The code below has the error:

TypeError: Cannot read property 'close' of undefined
    at Channel.push../src/app/tab1/tab1.page.ts.Tab1Page.loadStop (tab1-tab1-module.js:140)
    at Channel.fire (capacitor-runtime.js:1868)
    at InAppBrowser._eventHandler (capacitor-runtime.js:2715)
    at cb (capacitor-runtime.js:2775)
    at Object.callbackFromNative (capacitor-runtime.js:1362)
    at <anonymous>:1:9

on the line
this.iabRef.close();

Can I not reference this global variable from inside a callback function?
Any ideas?

I also tried declaring iabRef as public but no luck.

import { Component } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
declare var cordova: any;

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
  private iabRef;
  loadStopCounter = 0;

  constructor(private iab: InAppBrowser) { }

  buttonClick(link) {
    console.log('button click');

    const target = '_blank';
    const options = 'location=yes,zoom=no,hideurlbar=yes,hidenavigationbuttons=yes,closebuttoncaption=Click here to return to App,closebuttoncolor=#f04141';

    this.iabRef = cordova.InAppBrowser.open(link, target, options);
    // this.iabRef.close();  This works!!!

    this.iabRef.addEventListener('loadstop', this.loadStop);
  }

  loadStop(params, callback) {
    this.loadStopCounter++;

      if (params.url.substr(params.url.lastIndexOf('/') + 1) === 'formResponse') {
        // This does not work
        this.iabRef.close();
      }
  }
}

Resolved.
I got it working by using a local variable in the function.
If someone could explain why this works I would love to here it.

export class Tab1Page {

  constructor(private iab: InAppBrowser) { }

  buttonClick(link) {
    // const browser = this.iab.create('https://ionicframework.com/');
    console.log('button click');

    const target = '_blank';
    const options = 'location=yes,zoom=no,hideurlbar=yes,hidenavigationbuttons=yes,closebuttoncaption=Tap here to return to App,closebuttoncolor=#f04141';
    // const refLink = this.iab.create(link, target, options);

    const iabRef2 = cordova.InAppBrowser.open(link, target, options);

    iabRef2.addEventListener('loadstop', function(params, callback) {
      if (params.url.substr(params.url.lastIndexOf('/') + 1) === 'formResponse') {
        iabRef2.close();
      }
    });

  }
1 Like