📌  相关文章
📜  react native webview postmessage example - Javascript (1)

📅  最后修改于: 2023-12-03 15:04:49.108000             🧑  作者: Mango

React Native WebView PostMessage Example

In React Native, you may find yourself wanting to make use of WebViews to display web content within your app. However, in some cases you may want to communicate between the WebView and your React Native code. This is where postMessage comes in handy.

Example

Let's say we have a WebView component within our React Native app:

import React, { useRef } from 'react';
import { WebView } from 'react-native-webview';

const MyWebView = () => {
  const webViewRef = useRef(null);

  return (
    <WebView
      ref={webViewRef}
      source={{ uri: 'https://www.example.com' }}
    />
  );
};

To communicate between the WebView and our React Native code, we can use the WebView's postMessage function. We can define a onMessage function to handle messages received from the WebView:

import React, { useRef } from 'react';
import { WebView } from 'react-native-webview';

const MyWebView = () => {
  const webViewRef = useRef(null);

  const handleMessage = (event) => {
    const { data } = event.nativeEvent;
    console.log(`Received message from webview: ${data}`);
  }

  return (
    <WebView
      ref={webViewRef}
      source={{ uri: 'https://www.example.com' }}
      onMessage={handleMessage}
    />
  );
};

Now within our WebView, we can send messages back to our React Native code using the window.postMessage function:

<html>
  <body>
    <button onclick="sendMessage()">Send Message</button>
    <script>
      function sendMessage() {
        window.postMessage('Hello from WebView!');
      }
    </script>
  </body>
</html>

When the user clicks the "Send Message" button within the WebView, our handleMessage function in React Native will be called and log the message "Hello from WebView!" to the console.

Conclusion

Using postMessage, we can easily communicate between a WebView and our React Native code. This can open up new possibilities for integrating web content into our apps.