从 JavaScript 调用 Android 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22895140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:32:11  来源:igfitidea点击:

Call Android methods from JavaScript

javascriptandroidhtmlwebview

提问by bodruk

I searched, but I didn't find an answer. I'm developing an Android app based on webview, using HTML5 and JavaScript. Can I call an Android method, like makeToast()from JavaScript?

我搜索了,但没有找到答案。我正在使用 HTML5 和 JavaScript 开发基于 webview 的 Android 应用程序。我可以像makeToast()从 JavaScript一样调用 Android 方法吗?

回答by Ian

You can do this by adding a JavaScript Interface to your WebView and exposing specific methods to the JavaScript code running in your web view. In other words, you'll need to wrap the calls to Android's Toast class in a method you create in your activity/fragment.

您可以通过向 WebView 添加 JavaScript 接口并向 Web 视图中运行的 JavaScript 代码公开特定方法来实现此目的。换句话说,您需要在您在活动/片段中创建的方法中包装对 Android 的 Toast 类的调用。

activity_main.xml

活动_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView android:id="@+id/web_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"/>

</RelativeLayout>

MainActivity.java

主活动.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = (WebView)findViewById(R.id.web_view);
        webView.loadUrl("file:///android_asset/web.html");

        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");
    }

    /*
     * JavaScript Interface. Web code can access methods in here 
     * (as long as they have the @JavascriptInterface annotation)
     */
    public class WebViewJavaScriptInterface{

        private Context context;

        /*
         * Need a reference to the context in order to sent a post message
         */
        public WebViewJavaScriptInterface(Context context){
            this.context = context;
        }

        /* 
         * This method can be called from Android. @JavascriptInterface 
         * required after SDK version 17. 
         */
        @JavascriptInterface
        public void makeToast(String message, boolean lengthLong){
            Toast.makeText(context, message, (lengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT)).show();
        }
    }

}

assets/web.html

资产/web.html

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript View</title>

    <script type="text/javascript">

        function showToast(){
            var message = document.getElementById("message").value;
            var lengthLong = document.getElementById("length").checked;

            /* 
                Call the 'makeToast' method in the Java code. 
                'app' is specified in MainActivity.java when 
                adding the JavaScript interface. 
             */
            app.makeToast(message, lengthLong);
            return false;
        }

        /* 
            Call the 'showToast' method when the form gets 
            submitted (by pressing button or return key on keyboard). 
         */
        window.onload = function(){
            var form = document.getElementById("form");
            form.onsubmit = showToast;
        }
    </script>
</head>

<body>

<form id="form">
    Message: <input id="message" name="message" type="text"/><br />
    Long: <input id="length" name="length" type="checkbox" /><br />

    <input type="submit" value="Make Toast" />
</form>

</body>
</html>

A Toast Message

祝酒词

回答by Andrei Angurets

Just because it is more convenient (layout):

只是因为它更方便(布局):

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

回答by Amit Pandey

After creating your Main Activity code you need to create your Javascript code and call WebviewInterface from that, Let's see the example:

创建主活动代码后,您需要创建 Javascript 代码并从中调用 WebviewInterface,让我们看看示例:

public class MainActivity extends AppCompatActivity {

String TAG = "MainActivity";
Context context;
WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;

    mWebView = (WebView) findViewById(R.id.webview);
    initWebView();

    String ENROLLMENT_URL = "file:///android_asset/about_page.html";
    mWebView.loadUrl(ENROLLMENT_URL);

}

@SuppressLint({ "SetJavaScriptEnabled" })
private void initWebView() {
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.addJavascriptInterface(new WebviewInterface(), "Interface");
}

public class WebviewInterface {
    @JavascriptInterface
    public void javaMehod(String val) {
        Log.i(TAG, val);
        Toast.makeText(context, val, Toast.LENGTH_SHORT).show();
    }
}
}

activity_main.xml

活动_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.legendblogs.android.MainActivity">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webview"/>


</RelativeLayout>

Look at this link to see full example https://www.legendblogs.com/blog/how-to-call-native-java-methods-from-webview-javascript/121764

查看此链接以查看完整示例 https://www.legendblogs.com/blog/how-to-call-native-java-methods-from-webview-javascript/121764