如何从WebView发送消息到React Native? [英] How can I send a message from the WebView to React Native?

查看:366
本文介绍了如何从WebView发送消息到React Native?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地将消息从React Native(RN)发送到WebView.

I’ve successfully managed to send a message from React Native (RN) to a WebView.

我正在努力解决的问题是,将消息从WebView重新发送到RN.没有错误显示-只是消息永远不会通过.

What I’m struggling with, is getting the message back from the WebView to RN. There’s no errors showing - it’s just that the message never gets through.

这是我正在使用的代码:

Here is the code which I’m using:

反应本机代码

<WebView
  ref={webview => (this.webview = webview)}
  source={{ uri: "http://www.my-web-site"}}
  onLoadEnd={() => this.onLoadEnd()}
  onMessage={this.onMessage}
  cacheEnabled={false}
  originWhitelist={['*']}
  javaScriptEnabled={true}
/>

onLoadEnd() {
  this.webview.postMessage("RN message");
}

onMessage(message) {
  console.log("I can’t see this message!");
}

WebView代码

document.addEventListener("message", function (event) {
  setTimeout(function(){document.postMessage("WebView message")}, 3000);
}, false);

非常感谢.

推荐答案

请确保每个接收器的数据都在其中,并使用您需要的数据.

Please make sure that the data for each receiver is in and use the data that You need.

在使用它们之前,请务必先检查规定的文档以了解如何使用参数和语法.

And always check the prescribed documents to see how to use parameters and grammar before using them.

RN

onLoadEnd() {

  this.webview.postMessage("sendmessage");
}

onMessage(event) {
  alert(event.nativeEvent.data);
}

WebView代码

    document.addEventListener("message", function (event) {
        window.postMessage(event.data);
    });

反应本机版本5.0或更高版本

window.ReactNativeWebView.postMessage(event.data);

这篇关于如何从WebView发送消息到React Native?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆