Gathering detailed insights and metrics for react-native-postmessage-cat
Gathering detailed insights and metrics for react-native-postmessage-cat
Gathering detailed insights and metrics for react-native-postmessage-cat
Gathering detailed insights and metrics for react-native-postmessage-cat
Simplify the postMessage between RN webview content and RN react code.
npm install react-native-postmessage-cat
Typescript
Module System
Node Version
NPM Version
TypeScript (91.44%)
JavaScript (8.56%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
4 Stars
10 Commits
1 Forks
2 Watchers
2 Branches
1 Contributors
Updated on Jan 08, 2025
Latest Version
0.3.1
Package Id
react-native-postmessage-cat@0.3.1
Unpacked Size
83.73 kB
Size
20.18 kB
File Count
22
NPM Version
9.8.0
Node Version
20.5.1
Published on
Sep 07, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
4
2
Based on linonetwo/electron-ipc-cat, and used in TidGi-Mobile.
Passing object and type between React Native main process and WebView process simply via proxy.
In latest react-native-webview, the injectedJavaScriptBeforeContentLoaded
accepts stringified code, and you are required to passing data using postMessage. It requires tons of boilerplate code to build up this message bridge, just like the vanilla Redux.
Luckily we have frankwallis/electron-ipc-proxy which provide a good example about how to automatically build IPC channel for a class in the main process. But it doesn't work in react native, so here we have react-native-postmessage-cat
!
We wrap our react native side class, and can use them from the window.xxx
in the webview. All types are preserved, so you can get typescript intellisense just like using a local function.
1pnpm i react-native-postmessage-cat
Real use case in TidGi-Mobile's sync-adaptor
1/** workspaces.ts */ 2import { ProxyPropertyType } from 'react-native-postmessage-cat'; 3import type { ProxyDescriptor } from 'react-native-postmessage-cat/common'; 4 5export class Workspace implements IWorkspaceService { 6 /** 7 * Record from workspace id to workspace settings 8 */ 9 private workspaces: Record<string, IWorkspace> = {}; 10 public workspaces$: BehaviorSubject<Record<string, IWorkspace>>; 11 12 public async getWorkspacesAsList(): Promise<IWorkspace[]> { 13 return Object.values(this.workspaces).sort((a, b) => a.order - b.order); 14 } 15 16 public async get(id: string): Promise<IWorkspace | undefined> { 17 return this.workspaces[id]; 18 } 19 20 public get$(id: string): Observable<IWorkspace | undefined> { 21 return this.workspaces$.pipe(map((workspaces) => workspaces[id])); 22 } 23} 24 25export interface IWorkspaceService { 26 workspaces$: BehaviorSubject<Record<string, IWorkspace>>; 27 getWorkspacesAsList(): Promise<IWorkspace[]>; 28 get(id: string): Promise<IWorkspace | undefined>; 29 get$(id: string): Observable<IWorkspace | undefined>; 30} 31 32export const WorkspaceServiceIPCDescriptor: ProxyDescriptor = { 33 channel: WorkspaceChannel.name, 34 properties: { 35 workspaces$: ProxyPropertyType.Value$, 36 getWorkspacesAsList: ProxyPropertyType.Function, 37 get: ProxyPropertyType.Function, 38 get$: ProxyPropertyType.Function$, 39 }, 40};
1/** 2 * Provide API from main services to WebView 3 * This file should be required by BrowserView's preload script to work 4 */ 5import { useMemo } from 'react'; 6import { ProxyPropertyType, useRegisterProxy, webviewPreloadedJS } from 'react-native-postmessage-cat'; 7import type { ProxyDescriptor } from 'react-native-postmessage-cat/common'; 8 9import { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface'; 10 11const workspaceService = new WorkspaceService(); 12 13export const WikiViewer = () => { 14 const [webViewReference, onMessageReference] = useRegisterProxy(workspaceService, WorkspaceServiceIPCDescriptor) 15 const preloadScript = useMemo(() =>` 16 ${webviewPreloadedJS} 17 true; // note: this is required, or you'll sometimes get silent failures 18 `, []); 19 return ( 20 <WebViewContainer> 21 <WebView 22 source={{ html: wikiHTMLString }} 23 onMessage={onMessageReference.current} 24 ref={webViewReference} 25 injectedJavaScriptBeforeContentLoaded={runFirst} 26 /> 27 </WebViewContainer> 28 ); 29};
1/** renderer.tsx */ 2import 'react-native-postmessage-cat/fixContextIsolation'; 3 4 5import { IWorkspace } from '@services/workspaces'; 6import { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface'; 7 8// `window.PostMessageCat`'s type is same as `createProxy` in `'react-native-postmessage-cat/webview'` 9const workspaceService = window.PostMessageCat<IWorkspace>(WorkspaceServiceIPCDescriptor) 10 11const workspacesList$ = workspaceService.workspaces$.pipe(map<Record<string, IWorkspace>, IWorkspace[]>((workspaces) => Object.values(workspaces))); 12const workspace$ = workspaceService.get$(id)
1import { useMemo } from 'react'; 2import { ProxyPropertyType, useRegisterProxy, webviewPreloadedJS } from 'react-native-postmessage-cat'; 3import type { ProxyDescriptor } from 'react-native-postmessage-cat/common'; 4import { WebView } from 'react-native-webview'; 5import { styled } from 'styled-components/native'; 6import { useTiddlyWiki } from './useTiddlyWiki'; 7 8const WebViewContainer = styled.View` 9 flex: 2; 10 height: 100%; 11`; 12 13class WikiStorage { 14 save(data: string) { 15 console.log('Saved', data); 16 return true; 17 } 18} 19enum WikiStorageChannel { 20 name = 'wiki-storage', 21} 22export const WikiStorageIPCDescriptor: ProxyDescriptor = { 23 channel: WikiStorageChannel.name, 24 properties: { 25 save: ProxyPropertyType.Function, 26 }, 27}; 28const wikiStorage = new WikiStorage(); 29const tryWikiStorage = ` 30const wikiStorage = window.PostMessageCat(${JSON.stringify(WikiStorageIPCDescriptor)}); 31wikiStorage.save('Hello World').then(console.log); 32// play with it: window.wikiStorage.save('BBB').then(console.log) 33window.wikiStorage = wikiStorage; 34`; 35 36export const WikiViewer = () => { 37 const wikiHTMLString = useTiddlyWiki(); 38 const [webViewReference, onMessageReference] = useRegisterProxy(wikiStorage, WikiStorageIPCDescriptor); 39 const preloadScript = useMemo(() => ` 40 window.onerror = function(message, sourcefile, lineno, colno, error) { 41 if (error === null) return false; 42 alert("Message: " + message + " - Source: " + sourcefile + " Line: " + lineno + ":" + colno); 43 console.error(error); 44 return true; 45 }; 46 47 ${webviewPreloadedJS} 48 49 ${tryWikiStorage} 50 51 true; // note: this is required, or you'll sometimes get silent failures 52 `, []); 53 return ( 54 <WebViewContainer> 55 <WebView 56 source={{ html: wikiHTMLString }} 57 onMessage={onMessageReference.current} 58 ref={webViewReference} 59 injectedJavaScriptBeforeContentLoaded={preloadScript} 60 // Open chrome://inspect/#devices to debug the WebView 61 webviewDebuggingEnabled 62 /> 63 </WebViewContainer> 64 ); 65};
All Values
and Functions
will return promises on the renderer side, no matter how they have been defined on the source object. This is because communication happens asynchronously. For this reason it is recommended that you make them promises on the source object as well, so the interface is the same on both sides.
Use Value$
and Function$
when you want to expose or return an Observable stream across IPC.
Only plain objects can be passed between the 2 sides of the proxy, as the data is serialized to JSON, so no functions or prototypes will make it across to the other side.
Notice the second parameter of createProxy
- Observable
this is done so that the library itself does not need to take on a dependency to rxjs. You need to pass in the Observable constructor yourself if you want to consume Observable streams.
The channel specified must be unique and match on both sides of the proxy.
The packages exposes 2 entry points in the "main" and "browser" fields of package.json. "main" is for the main thread and "browser" is for the renderer thread.
See issue 1829, You must set onMessage or the window.ReactNativeWebView.postMessage method will not be injected into the web page..
So a default callback is provided, and will log this, this can be safely ignored.
Use import { useRegisterProxy } from 'react-native-postmessage-cat';
instead of "react-native-postmessage-cat/react-native"
.
You should reject an Error, other wise serialize-error
can't handle it well.
1- reject(errorMessage); 2+ reject(new Error(errorMessage));
No vulnerabilities found.
No security vulnerabilities found.