React-Native 中内嵌的webview 通常是H5页面。那么就可能会遇到需要交互的地方,所以就需要进行通信!!
以下的方法是亲测有效的!
但H5给RN发送消息的时候,不能在进入页面的时候直接触发,需要写在事件里。

H5给RN发送消息:

 if(window.postMessage) {
       window.postMessage(JSON.stringify({
          type: 'login',
        }));
}

RN接受消息:

 public handleMessage = (e) => {
    try {
      const action = JSON.parse(e.nativeEvent.data);
      // 登录类型消息
      if (action.type === "login") {
      		//做你的处理
      } catch (error) {
      console.log(error);
    }
}

RN给H5发送消息:

public sendLoginMessage() {
    this._webView.postMessage(JSON.stringify({
    	//你需要传递的消息
      type: "login"
    }));
  }
  或者是:
  public sendLoginMessage() {
    this._webView.postMessage(msg);
  }

H5接收消息:

document.addEventListener('message', function(msg) {
    console.log(msg);
    //如果需要获取msg里面的值。需要msg.data。
    //当时这个坑卡了好久,因为不方便查看msg里面的东西,直接用msg.是获取不到东西的。
    //还有,记住使用  JSON.parse(msg.data)  才能获取到你的东西!!!
});
Logo

智屏生态联盟致力于大屏生态发展,利用大屏快应用技术降低开发者开发、发布大屏应用门槛

更多推荐