我们如何在我们的 android 应用程序中执行 javascript 函数并获取返回值?

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

How we can execute a javascript function and get a return value in our android application?

javascriptandroidreturn

提问by Praful Bhatnagar

How we can execute a javascript function and get a return value in our android appplication ?

我们如何执行 javascript 函数并在我们的 android 应用程序中获取返回值?

We want to execute a javascript on a button press event, we need to pass parameters to the script and get return values, So we are using "WebChromeClient" to implement this, But we got Exception is "SyntaxError: Parse error at undefined:1"

我们想在按钮按下事件上执行一个 javascript,我们需要将参数传递给脚本并获取返回值,所以我们使用“WebChromeClient”来实现这一点,但我们得到的异常是“SyntaxError: Parse error at undefined:1 ”

Following is my code

以下是我的代码

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class FirstTab extends Activity 
{


    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
             setContentView(R.layout.regis);

            try{

                webView = (WebView) findViewById(R.id.webView1);
                webView.getSettings().setJavaScriptEnabled(true);
                webView.setWebChromeClient(new MyWebChromeClient());
                String customHtml = "<html><head><title>iSales</title><script type=\"text/javascript\"> function fieldsOnDelete(){ var x=123; return \"JIJO\"; } </script></head><body>hi</body></html>";
                webView.loadData(customHtml, "text/html","UTF-8");  

                }catch(Exception e)
                {
                     Log.v("JAC LOG",e.toString());
                }

        }
    public void onResume()
    {
        super.onResume();

            final Button button = (Button) findViewById(R.id.button1);
             button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 try{
                    webView.loadUrl("javascript:alert(javascript:fieldsOnDelete())");
                 }
                 catch(Exception e)
                 {
                     Log.v("JAC LOG",e.toString());

                 }
              } 
             });
    }


    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

        Log.v("LogTag", message);
          result.confirm();
          return true;
        }
    }


}

回答by Praful Bhatnagar

you can use mWebView.loadUrl("javascript:checkName");to call the method...

您可以使用 mWebView.loadUrl("javascript:checkName");调用该方法...

Then you can use addJavascriptInterface()to add a Java object to the Javascript environment. Have your Java script call a method on that Java object to supply its "return value".

然后您可以使用addJavascriptInterface()将 Java 对象添加到 Javascript 环境中。让您的 Java 脚本调用该 Java 对象上的方法以提供其“返回值”。

EDIT1: Or you can use following hack:

EDIT1:或者您可以使用以下技巧:

Add this Client to your WebView:

将此客户端添加到您的 WebView:

final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d("LogTag", message);
            result.confirm();
            return true;
        }
    }

Now in your java script call do:

现在在您的 java 脚本调用中执行以下操作:

webView.loadUrl("javascript:alert(functionThatReturnsSomething)");

Now in the onJsAlert call "message" will contain the returned value.

现在在 onJsAlert 调用中“ message”将包含返回值。

Edit2:

编辑2:

So it does not work if we call javascript method just after call to load the URL since the page loads take time. So I created a test program to test that...

因此,如果我们在调用加载 URL 后立即调用 javascript 方法,则它不起作用,因为页面加载需要时间。所以我创建了一个测试程序来测试......

Following is my html file (named test.html) store in the assets folder:

以下是我的 html 文件(名为 test.html)存储在资产文件夹中:

<html>
<head>
<script language="javascript">
    function fieldsOnDelete(message) {
        alert("i am called with " + message);
        window.myjava.returnValue(message + " JIJO");
    }
</script>
<title>iSales android</title>


</head>
<body></body>
</html>
</body>
</html>

Following is my java class that would get that i would add to java script as interface and it would receive the return value:

以下是我的 java 类,它将作为接口添加到 java 脚本中,并且它将接收返回值:

public class MyJS {

    public void returnValue(String string){
        Log.d(this.getClass().getSimpleName(), string);
    }

}

And following is my activity class:

以下是我的活动课:

public class CheckWebView extends Activity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_web_view);
        webView = (WebView) findViewById(R.id.webview);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onConsoleMessage(String message, int lineNumber,
                    String sourceID) {
                super.onConsoleMessage(message, lineNumber, sourceID);
                Log.d(this.getClass().getCanonicalName(), "message " + message
                        + "   :::line number " + lineNumber + "   :::source id "
                        + sourceID);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                // TODO Auto-generated method stub

                onConsoleMessage(consoleMessage.message(),
                        consoleMessage.lineNumber(), consoleMessage.sourceId());

                Log.d(this.getClass().getCanonicalName(), "message::::: "
                        + consoleMessage.message());

                return super.onConsoleMessage(consoleMessage);
            }
        });

        webView.addJavascriptInterface(new MyJS(), "myjava");
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginsEnabled(true);
        webView.getSettings().setAllowFileAccess(true);

        webView.loadUrl("file:///android_asset/test.html");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_check_web_view, menu);
        return true;
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        webView.loadUrl("javascript:fieldsOnDelete('name');");
        return super.onOptionsItemSelected(item);
    }

}

The key here is that there should be some time interval between the call to load html file from assets folder and the call to javascript:method. Here I am calling it from onOptionsItemSelectedand it is working fine.. if I move the webView.loadUrl("javascript:fieldsOnDelete('name');");to the end of the onCreate() method the it shows the error that it can not find fieldsOnDelete()method...

这里的关键是在调用从资产文件夹加载 html 文件和调用javascript:method. 我在这里调用它onOptionsItemSelected并且它工作正常..如果我将 移动 webView.loadUrl("javascript:fieldsOnDelete('name');");到 onCreate() 方法的末尾,它会显示它无法找到fieldsOnDelete()方法的错误......

Hope it Helps...

希望能帮助到你...

EDIT3:

编辑3:

Replace following in your code

在您的代码中替换以下内容

webView.loadUrl("javascript:alert(javascript:fieldsOnDelete())");

with

webView.loadUrl("javascript:alert(fieldsOnDelete())");

and try...

并尝试...

回答by Matt Gaunt

In Android KitKat there is a new method evaluateJavascript that has a callback for a return value. The callback returns a JSON value, object or array depending on what you return.

在 Android KitKat 中有一个新方法 evaluateJavascript 有一个返回值的回调。回调根据您返回的内容返回 JSON 值、对象或数组。

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // In KitKat+ you should use the evaluateJavascript method
            mWebView.evaluateJavascript(javascript, new ValueCallback<String>() {
                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                @Override
                public void onReceiveValue(String s) {
                    JsonReader reader = new JsonReader(new StringReader(s));

                    // Must set lenient to parse single values
                    reader.setLenient(true);

                    try {
                        if(reader.peek() != JsonToken.NULL) {
                            if(reader.peek() == JsonToken.STRING) {
                                String msg = reader.nextString();
                                if(msg != null) {
                                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                    } catch (IOException e) {
                        Log.e("TAG", "MainActivity: IOException", e);
                    } finally {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            // NOOP
                        }
                    }
                }
            });
        }

You can see a full example here: https://github.com/GoogleChrome/chromium-webview-samples/tree/master/jsinterface-example

你可以在这里看到一个完整的例子:https: //github.com/GoogleChrome/chromium-webview-samples/tree/master/jsinterface-example