是否可以从javascript调用java类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6606216/
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-16 08:08:46  来源:igfitidea点击:

is it posible to call java class from javascript?

javajavascriptandroid

提问by milind

I need to make some UI part in javascript for android application for that I'm writing some code in javascript and load it in android web view. Now, I want to call java class from javascript.

我需要在 javascript 中为 android 应用程序制作一些 UI 部分,因为我正在用 javascript 编写一些代码并将其加载到 android web 视图中。现在,我想从 javascript 调用 java 类。

Is it possible to call java class from javascript?

是否可以从javascript调用java类?

Thanks in Advance!

提前致谢!

采纳答案by Harun

回答by siliconeagle

its actually reall easy (and cool) use:

它实际上非常简单(而且很酷)使用:

webView.addJavascriptInterface(js, "pageObject");

js is a java object made in you activty (or somewhere where you init the webview), pageObject is the namespace identifier (variable) you can use with javaScript on your webpage.

js 是在您的活动(或您初始化 web 视图的某个地方)中创建的 java 对象, pageObject 是您可以在网页上与 javaScript 一起使用的名称空间标识符(变量)。

回答by Gregory

It's possible, but I wouldn't do it for your given use case :) (the UI could be done with the Android framework)

这是可能的,但我不会为您的给定用例这样做:)(UI 可以使用 Android 框架完成)

You can add what they call "Javascript Interfaces", which are basically links from Javascript to Java code. First, define a class to bind containing the methods you which to call, and add it to your WebView :

您可以添加他们所谓的“Javascript 接口”,它们基本上是从 Javascript 到 Java 代码的链接。首先,定义一个要绑定的类,其中包含您要调用的方法,并将其添加到您的 WebView 中:

    class HelloInterface  
    {  
        public void test(String name)  
        {  
            Log.i(TAG, "Hello " + name); 
        }  
    } 

    webview.addJavascriptInterface(new HelloInterface(), "HELLO");  

Then, from your javascript code, you can just call

然后,从您的 javascript 代码中,您可以调用

window.HELLO.test("Webview");