Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ionic Native / Cordova InAppBrowser: Multiple `executeScript` Promises

Ionic Native / Cordova InAppBrowser: Multiple executeScript Promises

I recently worked on a project with Ionic Native and Cordova. One thing I noticed (and took me some time to resolve), was an issue with the then function of the InAppBrowser plugin's executeScript Promise not being executed on iOS.

TL;DR When you use multiple executeScript Promises within one method, the then functions will not fire on iOS. You have to await results.

To illustrate the issue, let's declare a new InAppBrowser instance:

const browser = this.iab.create('https://example.com', '_blank');

Now, this would work just fine on Android:

browser.on('loadstop').subscribe(() => {
  browser.executeScript({code: 'window.location'}).then((location) => {
    // do something with location
  });
  browser.executeScript({code: 'document.cookie'}).then((cookies) => {
    // do something with cookies
  });
  browser.executeScript({code: 'console.log("foo")'});
});

However, the code above will fail on iOS. As soon as you use more than one executeScript call within the same method, it will no longer run into the then functions of the executeScript Promise.

Instead, you have to await the results to get it working on iOS. Here's the updated loadstop subscription method (note the async keyword for the callback function):

browser.on('loadstop').subscribe(async () => {
  let location: any = await this.iabResolveExecuteScript('window.location');
  // do something with location

  let cookies: any = await this.iabResolveExecuteScript('document.cookie');
  // do something with cookies
  
  browser.executeScript({code: 'console.log("foo")'});
});

And here's the helper method:

iabResolveExecuteScript(code: string) {
  return new Promise((resolve) => {
    browser.executeScript({code: code}).then((result) => {
      resolve(result);
    });
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment