Detect button click from WebView in React Native

后端 未结 2 1180
广开言路
广开言路 2021-01-07 05:30

Can anyone please help me on how to detect Webview button click event in React Native? As shown in the code below, I have a Button in my WebView (index.html) for which i wan

相关标签:
2条回答
  • 2021-01-07 06:12

    window.postMessage doesn't work for me for current last version. And found many other solutions that maybe worked for someone in some version but not for me.

    Check how I solve it with window.ReactNativeWebView.postMessage:

    "react": "16.13.1",
    "react-native": "0.63.3",
    "react-native-webview": "^11.0.2",
    

    Note: that I am using html string instead of url

    <WebView
        bounces={false}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}
        javaScriptEnabled={true}
        originWhitelist={['*']}
        source={{ html }}
        onLoadEnd={this.onLoadEnd}
        onError={this.onError}
        mixedContentMode={'never'} // security
        startInLoadingState={true} // when starting this component
        onMessage={onMessage}
        javaScriptEnabledAndroid={true}
    />
    
    onMessage = (message: string) => {
        console.log('action result coming from the webview: ', message);
    };
    

    And in the html string I added the script below and set the onclick for a given html button or a tag:

    ...
    <div>
        <button onclick="clickYourButton([PASS SOME STRING DATA HERE])">Click</button>
    </div>
    ...
    <script type="text/javascript">
        function clickYourButton(data) {
            setTimeout(function () {
                window.ReactNativeWebView.postMessage(data)
            }, 0) // *** here ***
        }
    </script>
    
    • Data to be passed to the postMessage func should be string type
    0 讨论(0)
  • 2021-01-07 06:23

    Add window.postMessage() to your page file and onMessage={this.onMessage} to your React Native WebView component.

    Example:

    // index.html (Web)
    ...
    <script>
      window.postMessage("Sending data from WebView");
    </script>
    ...
    
    
    // MyWebView.js (React Native)
    <WebView>
    ...
    <WebView
       ref="webview"
        onMessage={this.onMessage}
    />
      
    onMessage(data) {
      //Prints out data that was passed.
      console.log(data);
    }
    

    Edit: Working example:

    App.js

    onMessage(m) {
     alert(m.nativeEvent.data);
    }
    render() {
      return(
        <WebView
          style={{ flex: 1 }}
          source={{uri: 'http://127.0.0.1:8877'}} //my localhost
          onMessage={m => this.onMessage(m)} 
        />
      );
    }
    

    index.html

    <button>Send post message from web</button>
    
    <script>
    document.querySelector("button").onclick = function() {
      console.log("Send post message");
      window.postMessage("Hello React", "*");
    }
    </script>
    

    Hope it helps

    0 讨论(0)
提交回复
热议问题