### Install with npm Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/1.1-getting-started Install the package in both React (web) and React Native projects using npm. ```bash # Using npm npm i @cheeselemon/react-native-webview-bridge ``` -------------------------------- ### Install with yarn Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/1.1-getting-started Install the package in both React (web) and React Native projects using yarn. ```bash # Using yarn yarn add @cheeselemon/react-native-webview-bridge ``` -------------------------------- ### Native Implementation Example Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/1.1-getting-started Use the useReactNativeWebViewBridgeForReactNative hook with a WebView ref to inject JavaScript and handle incoming messages from the web app. ```jsx import React, { useRef } from 'react'; import WebView from 'react-native-webview'; import { useReactNativeWebViewBridgeForReactNative } from "@cheeselemon/react-native-webview-bridge"; function MyNativeComponent() { const webViewRef = useRef(null); // Initialize bridge with the WebView reference const { postMessage, handleMessage } = useReactNativeWebViewBridgeForReactNative(webViewRef); const notifyWeb = () => { postMessage("NATIVE_EVENT", { msg: "Hello from Native" }); }; return ( { // handleMessage parses the event and executes the callback if valid const handled = handleMessage(event, (eventName, data) => { console.log(`Received ${eventName} from Web:`, data); }); // Fallback for non-bridge messages if (!handled) { console.log("Standard WebView message:", event.nativeEvent.data); } }} /> ); } ``` -------------------------------- ### Web Implementation Example Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/1.1-getting-started Use the useReactNativeWebViewBridgeForReact hook in the web app to manage window event listeners and send messages to Native via postMessage. ```jsx import { useReactNativeWebViewBridgeForReact } from "@cheeselemon/react-native-webview-bridge"; function MyWebComponent() { // Destructure postMessage to send data to Native const { postMessage } = useReactNativeWebViewBridgeForReact({ handler: (eventName, data) => { console.log(`Received ${eventName} from Native:`, data); }, }); const notifyNative = () => { postMessage("WEB_EVENT", { status: "success" }); }; return ; } ``` -------------------------------- ### postMessage Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/2.2-react-native-(host)-hook-usereactnativewebviewbridgeforreactnative Sends data from the Host to the Guest (Web) by injecting a JavaScript string into the WebView that dispatches a MessageEvent. ```APIDOC ## postMessage ### Description Injects a message into the WebView's JavaScript context to trigger a DOM event. ### Parameters - `eventName` (string) - Required - The name of the event to send. - `data` (any) - Required - The data payload to send. ### Behavior 1. Serializes `eventName` and `data` into a JSON object. 2. Checks if `webViewRef.current` exists. 3. Injects JavaScript that constructs a `MessageEvent` using the shared `RNWB_EVENT_NAME` constant (`"rnwb:message"`). ``` -------------------------------- ### useReactNativeWebViewBridge Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/2.1-react-(web)-hook-usereactnativewebviewbridgeforreact The primary entry point for React web applications to communicate with a React Native host. It manages the lifecycle of message listeners on the window object and provides a structured interface for sending data back to the native layer. ```APIDOC ## useReactNativeWebViewBridge ### Description The `useReactNativeWebViewBridge` hook is the primary entry point for React web applications (the "Guest" side) to communicate with a React Native host. It manages the lifecycle of message listeners on the `window` object and provides a structured interface for sending data back to the native layer. ### Signature `useReactNativeWebViewBridge(handler?: (eventName: string, data: any) => void): { postMessage: (eventName: string, data: any) => void }` ### Parameters - **handler** (function) - Optional - A callback function that receives `eventName` and `data` when a message is received from the native side. ### Returns - **postMessage** (function) - A function to send structured data to the native side. It takes an `eventName` (string) and `data` (any), serializes them to JSON, and sends via `window.ReactNativeWebView.postMessage`. ### Global Interface: `window.ReactNativeWebView` - **ReactNativeWebView** (Object) - The bridge object injected by the React Native WebView component. - **ReactNativeWebView.postMessage** (function) - The native function used to send a raw string to the React Native side. ### Lifecycle - On mount, if `window` is available, it adds a listener for the event `'rnwb:message'` using `window.addEventListener`. - On unmount, the cleanup function removes the listener to prevent memory leaks. ### Internal `handlerBridge` - Parses the event object to extract `eventName` and `data`. - Calls the user-provided `handler` with the extracted parameters. - Catches any parsing or execution errors and logs them via `console.warn` to prevent the web app from crashing. ### Example ```javascript import { useReactNativeWebViewBridge } from 'react-native-webview-bridge'; function App() { const { postMessage } = useReactNativeWebViewBridge((eventName, data) => { console.log('Received from native:', eventName, data); }); const sendMessage = () => { postMessage('greeting', { text: 'Hello from web!' }); }; return ; } ``` ``` -------------------------------- ### handleMessage Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/2.2-react-native-(host)-hook-usereactnativewebviewbridgeforreactnative Middleware function to be passed into the onMessage prop of the WebView. Parses raw message strings into structured events and executes a callback. ```APIDOC ## handleMessage ### Description Parses incoming message data from the WebView and executes a callback with the event name and data. ### Parameters - `msg` (object) - Required - The message event object containing `nativeEvent.data`. - `cb` (function) - Required - Callback function `(eventName, data) => void`. ### Returns Always returns `false` due to a `finally` block overriding the `try` return. ``` -------------------------------- ### Serialization Logic: JSON.stringify Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/3-message-protocol Used on both sides of the bridge to serialize messages before transmission. Converts the eventName and data fields into a JSON string. ```javascript const msg = JSON.stringify({ eventName, data }); ``` -------------------------------- ### useReactNativeWebViewBridgeForReactNative Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/2.2-react-native-(host)-hook-usereactnativewebviewbridgeforreactnative The host-side hook for the bridge in a React Native environment. It accepts a webViewRef and returns handleMessage and postMessage methods for communication with the WebView. ```APIDOC ## useReactNativeWebViewBridgeForReactNative ### Description Host-side hook that provides handleMessage and postMessage methods for bridge communication with a WebView. ### Signature `useReactNativeWebViewBridgeForReactNative(webViewRef: RefObject)` ### Parameters - `webViewRef` (RefObject) - Required - A React RefObject pointing to an instance of react-native-webview. ### Returns An object containing: - `handleMessage` (function) - Decodes onMessage events from the WebView and triggers a callback. - `postMessage` (function) - Encodes data and injects it into the WebView as a MessageEvent. ``` -------------------------------- ### Message Protocol JSON Structure Source: https://deepwiki.com/cheeselemon/react-native-webview-bridge/6-glossary Defines the required JSON structure for messages exchanged through the bridge. The eventName is a unique identifier for the action/event, and data is the payload (string, object, number, etc.). ```json { eventName: string; // The unique identifier for the action/event data: any; // The payload (string, object, number, etc.) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.