ReactJS与Native Android中的Webview进行通信(‘Android’未定义为no-undef)

我在ReactJS中写了Web部分(不是React Native – 非常重要).我还有简单的Android应用程序,它包含WebView,我在那里打开网站,在ReactJS上运行.有没有正确的方法,如何在Android原生webview(打开ReactJS网站)和ReactJS网站之间进行通信?

顺便说一句.我已经完成了这个Facebook React Native Communication,但这是React Native的典型案例.这意味着,在通过ReactActivity扩展Activity等原生Android应用程序中,这是无用的……

这是ReactJS源代码,我想调用JS调用Mobile.showToast(“Test”)(不仅在这里,在很多地方,在许多.tsx文件中),但它根本没有编译项目.编译错误是’Mobile’未定义no-undef:

import * as React from "react";
import {
  Button,
} from "components";

class Login extends React.PureComponent {
  public render() {
    return (
      <Fullscreen>
        <Content>
          <Button onClick={this.handleRedirect} fullWidth>
        </Content>
      </Fullscreen>
    );
  }

  private handleRedirect = () => {
    //Here I wanted to call JS call for Android JavascriptInterface interrogation
    Mobile.showToast("Test");
  };
}

export default Login;

这是附加javascriptInterface JS调用的源代码(在本例中只调用showToast):

webView.addJavascriptInterface(new MobileAppInterface(getContext()), "Mobile");


import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

public class MobileAppInterface {

    Context mContext;

    /**
     * Instantiate the interface and set the context
     */
    public MobileAppInterface(Context c) {
        mContext = c;
    }

    /**
     * Show a toast from the web page
     */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

解决方法:

在您的React方法中,由于您将JavascriptInterface命名为“Mobile”,因此您需要修改您的方法以使用window.Mobile.showToast(“Test”);因为接口被导出到全局窗口对象

class Login extends React.PureComponent {

    ...

    private handleRedirect = () => {
        if (window.Mobile)
            window.Mobile.showToast("Test");
    };
}

例如,如果您将JavascriptInterface命名为“Android”,

webView.addJavascriptInterface(new MobileAppInterface(getContext()), "Android");

然后你的方法体需要如下:

class Login extends React.PureComponent {

    ...

    private handleRedirect = () => {
        if (window.Android)
            window.Android.showToast("Test");
    };
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...