Skip to content

Commit

Permalink
feat(react-native): postMessage broadcast options (#75)
Browse files Browse the repository at this point in the history
* feat(react-native): postMessage broadcast options

* docs: broadcast

* fix: docs

* feat: default value false

* fix: false

* refactor: early ret
  • Loading branch information
gronxb authored Oct 28, 2024
1 parent fe68ee6 commit 4c288b1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
17 changes: 17 additions & 0 deletions docs/using-a-post-message.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,20 @@ const unsubscribe2 = bridge.addEventListener("eventName2", (message) => {
});
unsubscribe2(); // Unsubscribe from the event
```


# Broadcast

Due to React Navigation and other factors, there can be multiple instances of a WebView. Sometimes, you may want to send messages to all WebView instances, while at other times, you may only want to target the last WebView instance (e.g., the top of the React Navigation stack).

To send a message to all WebView instances:
```ts
postMessage(..., ..., { broadcast: true });
```

To send a message only to the last WebView instance:
```ts
postMessage(..., ...); // @default false
// or
postMessage(..., ..., { broadcast: false });
```
26 changes: 21 additions & 5 deletions packages/react-native/src/createWebView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,17 +152,33 @@ export const createWebView = <
>(
eventName: EventName,
args: Args,
options: {
/**
* If `true`, the message will be broadcasted to all webviews.
* @default false
*/
broadcast: boolean;
} = {
broadcast: false,
},
) => {
let _args: any = args;
if (postMessageSchema) {
_args = postMessageSchema[eventName].validate(args);
}

for (const ref of webviewRefList) {
ref?.current?.injectJavaScript(
SAFE_NATIVE_EMITTER_EMIT(`postMessage/${String(eventName)}`, _args),
);
if (options.broadcast) {
for (const ref of webviewRefList) {
ref?.current?.injectJavaScript(
SAFE_NATIVE_EMITTER_EMIT(`postMessage/${String(eventName)}`, _args),
);
}
return;
}

const lastRef = webviewRefList[webviewRefList.length - 1];
lastRef?.current?.injectJavaScript(
SAFE_NATIVE_EMITTER_EMIT(`postMessage/${String(eventName)}`, _args),
);
},
WebView: forwardRef<BridgeWebView, WebViewProps>((props, ref) => {
const webviewRef = useRef<WebView>(null);
Expand Down

0 comments on commit 4c288b1

Please sign in to comment.