【问题标题】:How can I trigger action back in the react-native from my WebView?如何从我的 WebView 中触发反应原生的动作?
【发布时间】:2020-10-02 08:59:46
【问题描述】:

我有一个组件<PaymentView />,这个组件显示一个credit card/cvc/expiry form。

它使用 react-native-webview 在 react-native 应用程序中显示。

我必须触发表单事件并在提交时更新视图,提交按钮当前位于 WebView 中。

  • 在 webview 中按下提交 <Button /> 后,如何关闭 WebView 并显示成功消息?
  • 如果我无法从我的组件中获取 webview 提交事件,我如何从我的组件中读取 webview 中的表单?

【问题讨论】:

    标签: javascript reactjs react-native webview react-native-webview


    【解决方案1】:

    在处理 Web 应用程序中的支付 iframe 时,我通常会遇到这个问题。我认为解决方案是相同或类似的方法。

    检查postMessage API。

    我们通常做的是在 iFrame(我猜是你的 webView)端发出一个事件。通常是一个导航事件,然后我们在我们的应用程序中全局监听该事件,例如:

        <script>
    
            var defaultResponse = {
                status: 0,
                code: '',
                message: ''
            }
    
            function queryParamsToObject(search = '') {
                return search ? JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}') : ''
            }
    
            function getResponseObject() {
                return queryParamsToObject(decodeURI(location.search).substring(1))
            }
    
            var response = getResponseObject()
    
            console.log('window:child', window.parent, response)
            try {
                window.parent.postMessage(response, '*')
            } catch (e) {
                console.log('window:child:send:error', e)
            }
    
        </script>
    

    在快速搜索react-native-webview 时,我发现他们已经是using it

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      看看这个

        render() {
      const html = `
        <html>
        <head></head>
        <body>
          <script>
            setTimeout(function () {
              window.ReactNativeWebView.postMessage("Hello!")
            }, 2000)
          </script>
        </body>
        </html>
      `;
      
      return (
        <View style={{ flex: 1 }}>
          <WebView
            source={{ html }}
            onMessage={event => {
              alert(event.nativeEvent.data);
            }}
          />
        </View>
      );
      

      } }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-10
        • 1970-01-01
        • 2018-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-22
        • 1970-01-01
        相关资源
        最近更新 更多