{"id":23422709,"url":"https://github.com/linonetwo/react-native-postmessage-cat","last_synced_at":"2025-04-12T15:07:44.623Z","repository":{"id":190961092,"uuid":"683638946","full_name":"linonetwo/react-native-postmessage-cat","owner":"linonetwo","description":"Simplify the postMessage between RN webview content and RN react code.","archived":false,"fork":false,"pushed_at":"2023-12-15T14:26:48.000Z","size":349,"stargazers_count":4,"open_issues_count":1,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-12T15:07:40.435Z","etag":null,"topics":["bridge","invoke","post-message","postmessage","postmessage-library","proxy","react-native","react-native-webview","react-native-webview-bridge","webview"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/react-native-postmessage-cat","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/linonetwo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-08-27T08:11:59.000Z","updated_at":"2025-01-08T23:36:59.000Z","dependencies_parsed_at":"2023-12-15T15:43:09.768Z","dependency_job_id":null,"html_url":"https://github.com/linonetwo/react-native-postmessage-cat","commit_stats":null,"previous_names":["linonetwo/react-native-postmessage-cat"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/linonetwo%2Freact-native-postmessage-cat","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/linonetwo%2Freact-native-postmessage-cat/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/linonetwo%2Freact-native-postmessage-cat/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/linonetwo%2Freact-native-postmessage-cat/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/linonetwo","download_url":"https://codeload.github.com/linonetwo/react-native-postmessage-cat/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248586236,"owners_count":21128997,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bridge","invoke","post-message","postmessage","postmessage-library","proxy","react-native","react-native-webview","react-native-webview-bridge","webview"],"created_at":"2024-12-23T03:09:43.142Z","updated_at":"2025-04-12T15:07:44.603Z","avatar_url":"https://github.com/linonetwo.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# react-native-postmessage-cat\n\n\u003e Based on [linonetwo/electron-ipc-cat](https://github.com/linonetwo/electron-ipc-cat), and used in [TidGi-Mobile](https://github.com/tiddly-gittly/TidGi-Mobile]).\n\n\u003cp align=\"center\" style=\"color: #343a40\"\u003e\n  \u003cimg src=\"docs/image/title-image.png\" alt=\"electron-ipc-cat logo\"\u003e\n  \u003ch1 align=\"center\"\u003ereact-native-postmessage-cat\u003c/h1\u003e\n\u003c/p\u003e\n\u003cp align=\"center\" style=\"font-size: 1.2rem;\"\u003ePassing object and type between React Native main process and WebView process simply via proxy.\u003c/p\u003e\n\n## Overview\n\nIn 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.\n\nLuckily 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`!\n\nWe 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.\n\n## Install\n\n```sh\npnpm i react-native-postmessage-cat\n```\n\n## Example\n\nReal use case in [TidGi-Mobile's sync-adaptor](https://github.com/tiddly-gittly/TidGi-Mobile)\n\n### 1. The class\n\n```ts\n/** workspaces.ts */\nimport { ProxyPropertyType } from 'react-native-postmessage-cat';\nimport type { ProxyDescriptor } from 'react-native-postmessage-cat/common';\n\nexport class Workspace implements IWorkspaceService {\n  /**\n   * Record from workspace id to workspace settings\n   */\n  private workspaces: Record\u003cstring, IWorkspace\u003e = {};\n  public workspaces$: BehaviorSubject\u003cRecord\u003cstring, IWorkspace\u003e\u003e;\n\n  public async getWorkspacesAsList(): Promise\u003cIWorkspace[]\u003e {\n    return Object.values(this.workspaces).sort((a, b) =\u003e a.order - b.order);\n  }\n\n  public async get(id: string): Promise\u003cIWorkspace | undefined\u003e {\n    return this.workspaces[id];\n  }\n\n  public get$(id: string): Observable\u003cIWorkspace | undefined\u003e {\n    return this.workspaces$.pipe(map((workspaces) =\u003e workspaces[id]));\n  }\n}\n\nexport interface IWorkspaceService {\n  workspaces$: BehaviorSubject\u003cRecord\u003cstring, IWorkspace\u003e\u003e;\n  getWorkspacesAsList(): Promise\u003cIWorkspace[]\u003e;\n  get(id: string): Promise\u003cIWorkspace | undefined\u003e;\n  get$(id: string): Observable\u003cIWorkspace | undefined\u003e;\n}\n\nexport const WorkspaceServiceIPCDescriptor: ProxyDescriptor = {\n  channel: WorkspaceChannel.name,\n  properties: {\n    workspaces$: ProxyPropertyType.Value$,\n    getWorkspacesAsList: ProxyPropertyType.Function,\n    get: ProxyPropertyType.Function,\n    get$: ProxyPropertyType.Function$,\n  },\n};\n```\n\n### 2. bindServiceAndProxy in React Native side \u0026 bridge proxy in preload script\n\n```tsx\n/**\n * Provide API from main services to WebView\n * This file should be required by BrowserView's preload script to work\n */\nimport { useMemo } from 'react';\nimport { ProxyPropertyType, useRegisterProxy, webviewPreloadedJS } from 'react-native-postmessage-cat';\nimport type { ProxyDescriptor } from 'react-native-postmessage-cat/common';\n\nimport { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface';\n\nconst workspaceService = new WorkspaceService();\n\nexport const WikiViewer = () =\u003e {\n  const [webViewReference, onMessageReference] = useRegisterProxy(workspaceService, WorkspaceServiceIPCDescriptor)\n  const preloadScript = useMemo(() =\u003e`\n    ${webviewPreloadedJS}\n    true; // note: this is required, or you'll sometimes get silent failures\n  `, []);\n  return (\n    \u003cWebViewContainer\u003e\n      \u003cWebView\n        source={{ html: wikiHTMLString }}\n        onMessage={onMessageReference.current}\n        ref={webViewReference}\n        injectedJavaScriptBeforeContentLoaded={runFirst}\n      /\u003e\n    \u003c/WebViewContainer\u003e\n  );\n};\n```\n\n### 3. receive in JS that runs inside WebView\n\n```ts\n/** renderer.tsx */\nimport 'react-native-postmessage-cat/fixContextIsolation';\n\n\nimport { IWorkspace } from '@services/workspaces';\nimport { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface';\n\n// `window.PostMessageCat`'s type is same as `createProxy` in `'react-native-postmessage-cat/webview'`\nconst workspaceService = window.PostMessageCat\u003cIWorkspace\u003e(WorkspaceServiceIPCDescriptor)\n\nconst workspacesList$ = workspaceService.workspaces$.pipe(map\u003cRecord\u003cstring, IWorkspace\u003e, IWorkspace[]\u003e((workspaces) =\u003e Object.values(workspaces)));\nconst workspace$ = workspaceService.get$(id)\n```\n\n### Another example\n\n```tsx\nimport { useMemo } from 'react';\nimport { ProxyPropertyType, useRegisterProxy, webviewPreloadedJS } from 'react-native-postmessage-cat';\nimport type { ProxyDescriptor } from 'react-native-postmessage-cat/common';\nimport { WebView } from 'react-native-webview';\nimport { styled } from 'styled-components/native';\nimport { useTiddlyWiki } from './useTiddlyWiki';\n\nconst WebViewContainer = styled.View`\n  flex: 2;\n  height: 100%;\n`;\n\nclass WikiStorage {\n  save(data: string) {\n    console.log('Saved', data);\n    return true;\n  }\n}\nenum WikiStorageChannel {\n  name = 'wiki-storage',\n}\nexport const WikiStorageIPCDescriptor: ProxyDescriptor = {\n  channel: WikiStorageChannel.name,\n  properties: {\n    save: ProxyPropertyType.Function,\n  },\n};\nconst wikiStorage = new WikiStorage();\nconst tryWikiStorage = `\nconst wikiStorage = window.PostMessageCat(${JSON.stringify(WikiStorageIPCDescriptor)});\nwikiStorage.save('Hello World').then(console.log);\n// play with it: window.wikiStorage.save('BBB').then(console.log)\nwindow.wikiStorage = wikiStorage;\n`;\n\nexport const WikiViewer = () =\u003e {\n  const wikiHTMLString = useTiddlyWiki();\n  const [webViewReference, onMessageReference] = useRegisterProxy(wikiStorage, WikiStorageIPCDescriptor);\n  const preloadScript = useMemo(() =\u003e `\n    window.onerror = function(message, sourcefile, lineno, colno, error) {\n      if (error === null) return false;\n      alert(\"Message: \" + message + \" - Source: \" + sourcefile + \" Line: \" + lineno + \":\" + colno);\n      console.error(error);\n      return true;\n    };\n\n    ${webviewPreloadedJS}\n\n    ${tryWikiStorage}\n    \n    true; // note: this is required, or you'll sometimes get silent failures\n  `, []);\n  return (\n    \u003cWebViewContainer\u003e\n      \u003cWebView\n        source={{ html: wikiHTMLString }}\n        onMessage={onMessageReference.current}\n        ref={webViewReference}\n        injectedJavaScriptBeforeContentLoaded={preloadScript}\n        // Open chrome://inspect/#devices to debug the WebView\n        webviewDebuggingEnabled\n      /\u003e\n    \u003c/WebViewContainer\u003e\n  );\n};\n```\n\n### Multiple references\n\n```ts\nimport { useMergedReference } from 'react-native-postmessage-cat';\nimport { IWikiWorkspace } from '../store/wiki';\nimport { AppDataServiceIPCDescriptor } from './AppDataService/descriptor';\nimport { useAppDataService } from './AppDataService/hooks';\nimport { BackgroundSyncServiceIPCDescriptor } from './BackgroundSyncService/descriptor';\nimport { useBackgroundSyncService } from './BackgroundSyncService/hooks';\nimport { NativeServiceIPCDescriptor } from './NativeService/descriptor';\nimport { useNativeService } from './NativeService/hooks';\nimport { WikiStorageServiceIPCDescriptor } from './WikiStorageService/descriptor';\nimport { useWikiStorageService } from './WikiStorageService/hooks';\n\nconst registerServiceOnWebView = `\nwindow.service = window.service || {};\nvar wikiStorageService = window.PostMessageCat(${JSON.stringify(WikiStorageServiceIPCDescriptor)});\nwindow.service.wikiStorageService = wikiStorageService;\nvar backgroundSyncService = window.PostMessageCat(${JSON.stringify(BackgroundSyncServiceIPCDescriptor)});\nwindow.service.backgroundSyncService = backgroundSyncService;\nvar nativeService = window.PostMessageCat(${JSON.stringify(NativeServiceIPCDescriptor)});\nwindow.service.nativeService = nativeService;\nvar appDataService = window.PostMessageCat(${JSON.stringify(AppDataServiceIPCDescriptor)});\nwindow.service.appDataService = appDataService;\n`;\n\nexport function useRegisterService(workspace: IWikiWorkspace) {\n  const [wikiStorageServiceWebViewReference, wikiStorageServiceOnMessageReference] = useWikiStorageService(workspace);\n  const [backgroundSyncServiceWebViewReference, backgroundSyncServiceOnMessageReference] = useBackgroundSyncService();\n  const [nativeServiceWebViewReference, nativeServiceOnMessageReference] = useNativeService();\n  const [appDataServiceWebViewReference, appDataServiceOnMessageReference] = useAppDataService();\n\n  const mergedWebViewReference = useMergedReference(\n    wikiStorageServiceWebViewReference,\n    backgroundSyncServiceWebViewReference,\n    nativeServiceWebViewReference,\n    appDataServiceWebViewReference,\n  );\n\n  const mergedOnMessageReference = useMergedReference(\n    wikiStorageServiceOnMessageReference,\n    backgroundSyncServiceOnMessageReference,\n    nativeServiceOnMessageReference,\n    appDataServiceOnMessageReference,\n  );\n\n  return [mergedWebViewReference, mergedOnMessageReference, registerServiceOnWebView] as const;\n}\n```\n\nWhere `./WikiStorageService/hooks` is\n\n```ts\nimport { useMemo } from 'react';\nimport { useRegisterProxy } from 'react-native-postmessage-cat';\nimport { IWikiWorkspace } from '../../store/wiki';\nimport { WikiStorageService } from '.';\nimport { WikiStorageServiceIPCDescriptor } from './descriptor';\n\nexport function useWikiStorageService(workspace: IWikiWorkspace) {\n  const wikiStorageService = useMemo(() =\u003e new WikiStorageService(workspace), [workspace]);\n  const [webViewReference, onMessageReference] = useRegisterProxy(wikiStorageService, WikiStorageServiceIPCDescriptor, { debugLog: true });\n  return [webViewReference, onMessageReference] as const;\n}\n```\n\nUse it in React Component\n\n```tsx\n  const [webViewReference, onMessageReference, registerWikiStorageServiceOnWebView] = useRegisterService(wikiWorkspace);\n  const preloadScript = useMemo(() =\u003e `\n    ${webviewSideReceiver}\n    true; // note: this is required, or you'll sometimes get silent failures\n  `, [webviewSideReceiver]);\n\n  return (\n    \u003cWebView\n      originWhitelist={['*']}\n      // add DOCTYPE at load time to prevent Quirks Mode\n      source={{ html: `\u003c!doctype html\u003e\u003chtml lang=\"en\"\u003e\u003chead\u003e\u003cmeta charset=\"UTF-8\" /\u003e\u003c/head\u003e\u003cbody\u003e\u003c/body\u003e\u003c/html\u003e` }}\n      onMessage={onMessageReference.current}\n      ref={webViewReference}\n      injectedJavaScriptBeforeContentLoaded={preloadScript}\n      webviewDebuggingEnabled={true /* Open chrome://inspect/#devices to debug the WebView */}\n    /\u003e\n  );\n```\n\n## Notes\n\nAll `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.\n\nUse `Value$` and `Function$` when you want to expose or return an Observable stream across IPC.\n\nOnly 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.\n\nNotice 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.\n\nThe channel specified must be unique and match on both sides of the proxy.\n\nThe 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.\n\n## See it working\n\n[Example in TiddlyGit](https://github.com/tiddly-gittly/TiddlyGit-Desktop/blob/0c6b26c0c1113e0c66d6f49f022c5733d4fa85e8/src/preload/common/services.ts#L27-L42)\n\n## FAQ\n\n### WebView onMessage (before onMessageReference.current ready)\n\n[See issue 1829](https://github.com/react-native-webview/react-native-webview/issues/1829#issuecomment-1699235643), [You must set onMessage or the window.ReactNativeWebView.postMessage method will not be injected into the web page.](https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md#the-windowreactnativewebviewpostmessage-method-and-onmessage-prop).\n\nSo a default callback is provided, and will log this, this can be safely ignored.\n\n### Unable to resolve \"react-native-postmessage-cat/react-native\" from xxx\n\nUse `import { useRegisterProxy } from 'react-native-postmessage-cat';` instead of `\"react-native-postmessage-cat/react-native\"`.\n\n### reject string\n\nYou should reject an Error, other wise `serialize-error` can't handle it well.\n\n```diff\n- reject(errorMessage);\n+ reject(new Error(errorMessage));\n```\n\n## Change Log\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flinonetwo%2Freact-native-postmessage-cat","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flinonetwo%2Freact-native-postmessage-cat","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flinonetwo%2Freact-native-postmessage-cat/lists"}