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

问题描述 投票:4回答:1

我在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' is not defined 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();
    }
}
android reactjs react-native
1个回答
2
投票

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

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

资源

  1. 全局窗口对象https://developer.mozilla.org/en-US/docs/Glossary/Global_object
© www.soinside.com 2019 - 2024. All rights reserved.