IONIC: how to use postMessage to send data more securely

Diego Caceres
Pragma
Published in
3 min readAug 7, 2023

Hello community 👋🏻, In this post, I want to share how to use postMessage in your Ionic application or any other hybrid application and how to receive messages in your Angular or React application.

Problem Statement

In modern mobile applications, especially those built with frameworks like Ionic, there are often requirements to communicate between different web contexts, such as an in-app browser and the main app. This need arises when your app must interact with third-party content, such as authentication services, payment gateways, or external data sources. The challenge is to do this securely, avoiding vulnerabilities like cross-site scripting (XSS) and ensuring data integrity.

What is postMessage?

If you’re unfamiliar with postMessage, it's a native HTML method that allows you to send data to a window, popup, or iframe securely and easily. This can be a great alternative to using localStorage for cross-origin communication.

Practical Example

Imagine you have an Ionic mobile application that needs to authenticate users via an external OAuth service hosted in a web view. After successful authentication, the service needs to send a token back to your Ionic app. Using postMessage ensures that this token is transmitted securely.

Implementing postMessage in an Ionic Application

Setting Up the Ionic Application

In this example, we’ll use the InAppBrowser plugin to open the OAuth service in a web view and then send the authentication token back to the main app.

  1. Install the InAppBrowser Plugin:
ionic cordova plugin add cordova-plugin-inappbrowser
npm install @ionic-native/in-app-browser

2. Modify the Ionic Code:

Use the InAppBrowser to open a new window and send a message upon successful authentication:

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 {
constructor(private iab: InAppBrowser) {}

authenticateUser() {
const authUrl = 'https://example.com/oauth';
const browser = this.iab.create(authUrl, '_blank', 'location=yes');

browser.on('loadstop').subscribe(async () => {
try {
await browser.executeScript({
code: `
const eventHandshake = new CustomEvent('handshake', {
detail: { message: 'auth_token_12345' }
});
document.dispatchEvent(eventHandshake);
`,
});
} catch (e) {
console.log('Error:', e);
}
});
}
}

This code opens a new browser window for the OAuth service and, once authentication is complete, sends an authentication token back to the main app using a custom event named handshake.

Handling the Message in an Angular Application

To receive and handle the message in an Angular application, set up an event listener:

  1. Add the Event Listener: In your Angular application, listen for the handshake event and handle the received message:
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class HandshakeResolver implements Resolve<void> {
data: any;

resolve(): Promise<void> {
return new Promise((resolve) => {
const handshakeListener = (event: any) => {
this.data = event.detail?.message;

if (this.data) {
document.removeEventListener('handshake', handshakeListener);
resolve(this.data);
}
};

document.addEventListener('handshake', handshakeListener);
});
}
}

2. Use the Resolver in Your Routing Module:

Configure your app-routing.module.ts to use the resolver:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HandshakeResolver } from './handshake.resolver';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
{
path: '',
component: HomeComponent,
resolve: { handshakeData: HandshakeResolver },
},
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}

This setup ensures that the authentication token is resolved before the main component is loaded, making the token available throughout the application.

Conclusion

Using postMessage in your Ionic and Angular applications allows for secure and efficient cross-origin communication. This method is straightforward and can be easily implemented to enhance data exchange between different windows or iframes.

Happy coding! 🙌🏻

--

--

Diego Caceres
Pragma
Writer for

Software developer / Engineer. Learner of the life 🍃