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

event-driven-webview-bridge-react

v1.0.7

Published

The `event-driven-webview-bridge-react` library enables seamless and structured communication between React Native applications and web content within WebViews. <br /> By utilizing an event-driven architecture, it allows the WebView layers to send message

Downloads

505

Readme

EVENT-DRIVEN-WEBVIEW-BRIDGE-REACT

The event-driven-webview-bridge-react library enables seamless and structured communication between React Native applications and web content within WebViews. By utilizing an event-driven architecture, it allows the WebView layers to send messages, trigger actions, and handle responses with ease. The library provides a plugin-based design for extending functionality, ensuring that complex interactions are managed efficiently. Additionally, it includes built-in mechanisms for type safety, message queuing, and error handling, making it a robust solution for integrating React Native applications and web-based interfaces.

Key Features

  • Event-Driven Communication: Centralized event handling for all message exchanges between the react native app and WebView.

  • Plugin-Based Architecture: Easily extend the bridge's functionality using plugins for different purposes such as navigation, state management, and custom logic.

  • Promise-Based Messaging: All messages sent to the react native app are handled asynchronously, making it straightforward to manage request-response patterns.

  • Type Safety: Enjoy type inference for all communication-related code, reducing runtime errors and improving developer experience.

  • Queue Management: A built-in queue mechanism for handling message delivery to the react native app, ensuring reliable communication even when the window.ReactNativeWebView is not ready.

  • Guaranteed Message Order: All outgoing messages are processed using a timestamp-based sequential handling mechanism, ensuring that messages are delivered in the correct order even when multiple messages are sent concurrently.

Installation

Install the package via your preferred package manager:

# Using npm
npm install event-driven-webview-bridge-react

# Using yarn
yarn add event-driven-webview-bridge-react

# Using pnpm
pnpm add event-driven-webview-bridge-react

Getting Started

The basic setup involves creating a bridge instance, registering plugins, and managing communication events. Here's a quick overview:

  1. Set up the Bridge

    Import the library and initialize the bridge by providing a WebView reference.

    import ReactWebViewBridge from "event-driven-webview-bridge-react";
    
    // Initialize the bridge with plugins
    const bridge = ReactWebViewBridge.getInstance({
      plugins: {
        // Define your custom plugins here
      },
    });
  2. Trigger Plugin Actions

    The library's plugin-based architecture allows you to modularize your logic. After defining your plugins during the bridge initialization (getInstance), you can easily trigger their actions using the bridge.

    // Trigger plugin actions with parameters specific to your plugin after specifying the plugin name.
    bridge.triggerPluginActions("yourPluginName", {
      /* your parameters here */
    });
  3. Post Messages to the React Native App

    Use the postMessage method to send data to the WebView and receive a response asynchronously.

    const response = await bridge.postMessage({
      type: "navigation",
      data: { targetScreen: "HomePage" },
    });
  4. Handle Incoming Messages

    Set up message handlers to properly process and respond to messages sent from the React native app to the WebView. This ensures smooth communication and allows your web to app to various events triggered from the app.

    bridge.onMessage("toRNMessage", (message: MessagePayload) => {
      setMessage(`${message.type}: ${message.data}`);
    });

Plugin-Based Architecture

One of the core strengths of event-driven-webview-bridge-react is its plugin-based design. You can define and use plugins to encapsulate specific logic and manage complex interactions.

Creating a Plugin

To create a plugin, define a module that adheres to the following interface:

import { WebViewBridgePlugin } from "event-driven-webview-bridge-core/core/Plugin";

interface WebViewBridgePlugin {
  execute: (params: any) => void;
  cleanup?: () => void;
}
const customPlugin = new WebViewBridgePlugin((message: string) => {
  console.log("Custom plugin executed with:", message);
});

Adding Plugins to the Bridge

Plugins can be registered during the bridge initialization:

const bridge = ReactWebViewBridge.getInstance({
  plugins: { customPlugin },
});

API Reference

Class: ReactWebViewBridge<P extends PluginMap>

This class manages the communication between a React Native app and a WebView by using a plugin system. It allows for sending messages, triggering plugin actions, and handling incoming messages from the React Native App.

Properties

  • pluginManager:

    • An instance of WebViewBridgePluginManager responsible for managing registered plugins.
  • messageEventHandler:

    • An instance of ReactMessageEventHandler that handles incoming message events.
  • messageQueue:

    • An instance of ReactMessageQueue that manages the queuing of messages sent to the React Native App.

Static Methods

getInstance<P extends PluginMap>(options: WebBridgeOptions<P>): ReactWebViewBridge<P>

  • Description:

    • Retrieves the singleton instance of ReactWebViewBridge. If no instance exists, it creates one with the provided options.
  • Parameters:

    • options: An object containing the following properties:
      • plugins: An object mapping plugin names to their instances.
  • Returns:

    • An instance of ReactWebViewBridge.

Instance Methods

cleanup(): void

  • Description:

    • Cleans up the plugin manager and resets the singleton instance.
  • Returns:

    • None.

triggerPluginActions<K extends keyof P>(pluginName: K, ...args: Parameters<P[K]["execute"]>): void

  • Description:

    • Triggers actions defined in the specified plugin with the provided arguments.
  • Parameters:

    • pluginName: The name of the plugin to trigger.
    • ...args: The arguments to pass to the plugin's execute method.
  • Returns:

    • None.

postMessage(message: { type: MessagePayload["type"]; data: MessagePayload["data"] }): Promise<{ success: boolean }>

  • Description:

    • Sends a message to the WebView, adding a timestamp to the message.
  • Parameters:

    • message: An object containing:
      • type: The type of the message.
      • data: The payload of the message.
  • Returns:

    • A Promise that resolves to an object indicating success.

addMessageHandler(type: MessagePayload["type"], handler: MessageHandlerFunction): void

  • Description:

    • Adds a message handler for a specific message type.
  • Parameters:

    • type: The type of message to handle.
    • handler: A function that handles the message event.
  • Returns:

    • None.

onMessage(event: WebViewMessageEvent): void

  • Description:

    • Handles incoming message events from the WebView.
  • Parameters:

    • event: The WebView message event.
  • Returns:

    • None.

getPlugins(): P

  • Description:

    • Returns the list of registered plugins.
  • Returns:

    • An object mapping plugin names to their instances.

isReactNativeWebView(): boolean

  • Description:

    • Checks if the current environment is a React Native WebView. This method ensures that the application is running within a WebView context, allowing for specific handling or optimizations.
  • Returns:

    • A boolean value indicating whether the current environment is a React Native WebView (true) or not (false).

Contributing

We welcome contributions! Please see our Contributing Guide for details on how to get involved.

License

event-driven-webview-bridge-react is licensed under the MIT License. See the LICENSE file for more information.