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, thethen
functions will not fire on iOS. You have toawait
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);
});
});
}