Cross-Process Communication with RemoteMessenger

System Design · flowchart diagram · NOASSERTION

Illustrates the asynchronous communication flow between a Main Process and a WebView using a RemoteMessenger pattern, leveraging postMessage for Inter-Proc

Source: https://github.com/laurent22/joplin/blob/7f55a566e5a95e24cbfd7792cd7baf07ba46dc10/readme/dev/spec/plugins.md
Curated by laurent22
IPC WebView Main Process RemoteMessenger Asynchronous Communication JavaScript System Architecture

Mermaid source

flowchart
	postMessage(["postMessage({ kind: ReturnValueResponse, ... })"])
	rm2--6-->postMessage--7-->rm1
	subgraph WebView
		rm2["RemoteMessenger< WebViewApi,MainProcessApi >"]
		webViewApiImpl["webViewApiImpl.setCss"]
		webViewApiImpl--5-->rm2
	end
	subgraph MainProcess
		rm1["m1 = RemoteMessenger< MainProcessApi,WebViewApi >"]
		callMethod(["await m1.remoteApi.setCss('...')"])
		rm1--8-->callMethod
	end

What this diagram shows

This flowchart details the mechanism for inter-process communication (IPC) between a Main Process and a WebView. It specifically demonstrates how a 'callMethod' in the Main Process, such as 'm1.remoteApi.setCss', initiates a request via 'RemoteMessenger' (rm1), which then uses 'postMessage' to send the request to the WebView. Inside the WebView, another 'RemoteMessenger' (rm2) receives the message, invokes the 'webViewApiImpl.setCss' method, and then returns the result back to the Main Process using 'postMessage' with a 'ReturnValueResponse' kind, ultimately resolving the initial 'callMethod'.

When to use it

Use this pattern when building applications that require secure and structured communication between different isolated processes, such as a main application process and embedded web views or sandboxed environments. It's ideal for scenarios where the main process needs to invoke methods or exchange data with the web view asynchronously, and vice-versa.

How to adapt it for your project

This pattern can be adapted by defining different 'WebViewApi' and 'MainProcessApi' interfaces to expose various methods and data structures for communication. The 'RemoteMessenger' can be extended to include features like message validation, error handling, or richer serialization formats. It can also be generalized for communication between any two isolated processes, not just WebView and Main Process, by replacing 'postMessage' with other IPC mechanisms like message queues or sockets.

Key concepts