Search code examples
cordovaionic-frameworkiframeinappbrowserpostmessage

How to use postMessage with the ionic in-app-browser plugin?


Since the version 3.1.0-dev of the Cordova in-app-browser module, it appears that we can use the postMessage API in the following way:

webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj);

Howerver, after a long searrch, I dind't succeeded at making it works. It always fails silently. Furthermore, the webkit object is absent... As advised in this issue, I submit a valid JSON string. Please, find below an extract of my package.json file:

{
  "dependencies": {
     "@angular/core": "~8.1.2",
     "@ionic-native/core": "^5.16.0",
     "@ionic-native/in-app-browser": "^5.16.0",
     "cordova-plugin-inappbrowser": "git+https://github.com/apache/cordova-plugin-inappbrowser.git"
   }
}

I checked the cordova in-app-browser version with npm list –depth=0 and I have the 3.1.1-dev installed. Do you have any idea guys? Do no hesitate if you need more information. :-)

EDIT: I would like to send data from the iframe to my "main thread". To achieve that, I used the executeScript method which inject a script in the iframe. But sadly, I have no webkit object in it.

this.ref = this.iab.create("https://google.com", "_blank", "EnableViewPortScale=yes,location=no,hidden=false");
this.ref.on('loadstop').subscribe(event => {
  this.ref.executeScript({
                code: 'webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify({foo:"bar"});'
            });
});

Solution

  • When I was testing my app, I used the command ionic serve --devapp and used the app Ionic DevApp on my Android phone. Thus, it looks like it is not a real Android native app. I quote the cordova inappbrowser git repo:

    Browser Quirks loadstart, loaderror, message events are not fired.

    I installed an Android emulator on my laptop and I succeeded at transmitting a postMessage from my "iframe" to my "main thread".