Reputation: 577
I am trying to send a custom payload from my js inside my inAppBrowser to my ionic app. I already know how to send data to the inAppbrowser using:
iab.executeScript({code:`alert(2)`});
but sending data back is not properly documented, on the github site I saw:
inAppBrowserRef.addEventListener('message', messageCallBack);
the above only shows how to make your ionic receive it, but does not show how the javascript is sending it. Please I need help on how to make the inAppbrowser send this custom message.
Upvotes: 1
Views: 1668
Reputation: 11
If the child page being opened in App is under your control, you can put this into the webpage
inside webpage
window.parent.postMessage({msg : 'I am message'}, '*');
inside App
window.onmessage = (event) => {
console.log('event received in app', event);
}
Upvotes: 1
Reputation: 577
import { Component } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
ref: InAppBrowser;
constructor(private iab: InAppBrowser) {
}
openBlank() {
var payload = JSON.stringify({
"currency": "",
"exp": "",
"success_title": "",
"success_message": ""
})
var init = false;
var ref = this.iab.create('https://random.com/', '_blank', 'location=yes');
ref.on('loadstop').subscribe(event => {
if(!init){
console.log(' jeffery received')
//ref.executeScript({ code: "webkit.messageHandlers.cordova_iab.postMessage('"+payload+"')" });
ref.executeScript({ code: "jsFunction('" + payload + "');" });
init = true;
}
});
ref.on('message').subscribe((event) => {
const postObject:any = event
console.log(postObject.data.type)
console.log(JSON.stringify(postObject.data))
})
ref.on('loadstart').subscribe(event => {
if(init){
var shouldClose = this.getUrlParameter(event.url.replace(/%22/g, "\""), "shouldClose");
if(shouldClose){
var data = this.getUrlParameter(event.url.replace(/%22/g, "\""), "data");
var jsonObj = JSON.parse(data);
ref.close();
}
}
});
}
getUrlParameter = (url, name) => {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(url);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
openSystem() {
this.iab.create(`https://jamibot.com`, `_system`);
}
}
Upvotes: 1