npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-native-postmessage-cat

v0.3.1

Published

Passing object and type between React Native main process and WebView process simply via proxy.

Downloads

15

Readme

react-native-postmessage-cat

Based on linonetwo/electron-ipc-cat, and used in TidGi-Mobile.

Overview

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.

Install

pnpm i react-native-postmessage-cat

Example

Real use case in TidGi-Mobile's sync-adaptor

1. The class

/** workspaces.ts */
import { ProxyPropertyType } from 'react-native-postmessage-cat';
import type { ProxyDescriptor } from 'react-native-postmessage-cat/common';

export class Workspace implements IWorkspaceService {
  /**
   * Record from workspace id to workspace settings
   */
  private workspaces: Record<string, IWorkspace> = {};
  public workspaces$: BehaviorSubject<Record<string, IWorkspace>>;

  public async getWorkspacesAsList(): Promise<IWorkspace[]> {
    return Object.values(this.workspaces).sort((a, b) => a.order - b.order);
  }

  public async get(id: string): Promise<IWorkspace | undefined> {
    return this.workspaces[id];
  }

  public get$(id: string): Observable<IWorkspace | undefined> {
    return this.workspaces$.pipe(map((workspaces) => workspaces[id]));
  }
}

export interface IWorkspaceService {
  workspaces$: BehaviorSubject<Record<string, IWorkspace>>;
  getWorkspacesAsList(): Promise<IWorkspace[]>;
  get(id: string): Promise<IWorkspace | undefined>;
  get$(id: string): Observable<IWorkspace | undefined>;
}

export const WorkspaceServiceIPCDescriptor: ProxyDescriptor = {
  channel: WorkspaceChannel.name,
  properties: {
    workspaces$: ProxyPropertyType.Value$,
    getWorkspacesAsList: ProxyPropertyType.Function,
    get: ProxyPropertyType.Function,
    get$: ProxyPropertyType.Function$,
  },
};

2. bindServiceAndProxy in React Native side & bridge proxy in preload script

/**
 * Provide API from main services to WebView
 * This file should be required by BrowserView's preload script to work
 */
import { useMemo } from 'react';
import { ProxyPropertyType, useRegisterProxy, webviewPreloadedJS } from 'react-native-postmessage-cat';
import type { ProxyDescriptor } from 'react-native-postmessage-cat/common';

import { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface';

const workspaceService = new WorkspaceService();

export const WikiViewer = () => {
  const [webViewReference, onMessageReference] = useRegisterProxy(workspaceService, WorkspaceServiceIPCDescriptor)
  const preloadScript = useMemo(() =>`
    ${webviewPreloadedJS}
    true; // note: this is required, or you'll sometimes get silent failures
  `, []);
  return (
    <WebViewContainer>
      <WebView
        source={{ html: wikiHTMLString }}
        onMessage={onMessageReference.current}
        ref={webViewReference}
        injectedJavaScriptBeforeContentLoaded={runFirst}
      />
    </WebViewContainer>
  );
};

3. receive in JS that runs inside WebView

/** renderer.tsx */
import 'react-native-postmessage-cat/fixContextIsolation';


import { IWorkspace } from '@services/workspaces';
import { WorkspaceServiceIPCDescriptor } from '@services/workspaces/interface';

// `window.PostMessageCat`'s type is same as `createProxy` in `'react-native-postmessage-cat/webview'`
const workspaceService = window.PostMessageCat<IWorkspace>(WorkspaceServiceIPCDescriptor)

const workspacesList$ = workspaceService.workspaces$.pipe(map<Record<string, IWorkspace>, IWorkspace[]>((workspaces) => Object.values(workspaces)));
const workspace$ = workspaceService.get$(id)

Another example

import { useMemo } from 'react';
import { ProxyPropertyType, useRegisterProxy, webviewPreloadedJS } from 'react-native-postmessage-cat';
import type { ProxyDescriptor } from 'react-native-postmessage-cat/common';
import { WebView } from 'react-native-webview';
import { styled } from 'styled-components/native';
import { useTiddlyWiki } from './useTiddlyWiki';

const WebViewContainer = styled.View`
  flex: 2;
  height: 100%;
`;

class WikiStorage {
  save(data: string) {
    console.log('Saved', data);
    return true;
  }
}
enum WikiStorageChannel {
  name = 'wiki-storage',
}
export const WikiStorageIPCDescriptor: ProxyDescriptor = {
  channel: WikiStorageChannel.name,
  properties: {
    save: ProxyPropertyType.Function,
  },
};
const wikiStorage = new WikiStorage();
const tryWikiStorage = `
const wikiStorage = window.PostMessageCat(${JSON.stringify(WikiStorageIPCDescriptor)});
wikiStorage.save('Hello World').then(console.log);
// play with it: window.wikiStorage.save('BBB').then(console.log)
window.wikiStorage = wikiStorage;
`;

export const WikiViewer = () => {
  const wikiHTMLString = useTiddlyWiki();
  const [webViewReference, onMessageReference] = useRegisterProxy(wikiStorage, WikiStorageIPCDescriptor);
  const preloadScript = useMemo(() => `
    window.onerror = function(message, sourcefile, lineno, colno, error) {
      if (error === null) return false;
      alert("Message: " + message + " - Source: " + sourcefile + " Line: " + lineno + ":" + colno);
      console.error(error);
      return true;
    };

    ${webviewPreloadedJS}

    ${tryWikiStorage}
    
    true; // note: this is required, or you'll sometimes get silent failures
  `, []);
  return (
    <WebViewContainer>
      <WebView
        source={{ html: wikiHTMLString }}
        onMessage={onMessageReference.current}
        ref={webViewReference}
        injectedJavaScriptBeforeContentLoaded={preloadScript}
        // Open chrome://inspect/#devices to debug the WebView
        webviewDebuggingEnabled
      />
    </WebViewContainer>
  );
};

Notes

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 it working

Example in TiddlyGit

FAQ

WebView onMessage (before onMessageReference.current ready)

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.

Unable to resolve "react-native-postmessage-cat/react-native" from xxx

Use import { useRegisterProxy } from 'react-native-postmessage-cat'; instead of "react-native-postmessage-cat/react-native".

reject string

You should reject an Error, other wise serialize-error can't handle it well.

- reject(errorMessage);
+ reject(new Error(errorMessage));

Change Log