简体   繁体   English

如何从我的 WebView 中触发回 react-native 的动作?

[英]How can I trigger action back in the react-native from my WebView?

I have a component <PaymentView /> , this component display a credit card/cvc/expiry form.我有一个组件<PaymentView /> ,该组件显示一个信用卡/cvc/到期表单。

It is displayed in a react-native application usingreact-native-webview .它使用react-native-webview显示在 react-native 应用程序中。

I must trigger the form event and update the view on submit, the submit button is currently within the WebView.我必须触发表单事件并在提交时更新视图,提交按钮当前位于 WebView 内。

  • After pressing the submit <Button /> from within the webview, how can I close the WebView and display a success message?从 webview 中按下提交<Button />后,如何关闭 WebView 并显示成功消息?
  • If I can't get the webview submit event from within my component, how can I read the form within the webview from my component?如果我无法从我的组件中获取 webview 提交事件,我如何从我的组件中读取 webview 中的表单?

I usually have this problem when dealing with payment iframes in web applications.在 web 应用程序中处理支付 iframe 时,我通常会遇到这个问题。 I think the solution is the same or a similar approach.我认为解决方案是相同或相似的方法。

Check the postMessage API.检查postMessage API。

What we usually do, is emit an event on the iFrame (your webView i guess) side.我们通常做的是在 iFrame(我猜是你的 webView)端发出一个事件。 Usually is a navigation event, and then we listen for that event globally in our app like:通常是一个导航事件,然后我们在我们的应用程序中全局监听该事件,例如:

    <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>

On a fast search to react-native-webview i see that they are already using it在快速搜索react-native-webview时,我发现他们已经在使用它

Hope it helps希望能帮助到你

check out this看看这个

  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>
);

} } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM