WebView 到 JS 调用函数

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

在java代码(容器)中,我必须通过调用一些javascript函数来获取一些值,为此我使用webView.evaluateJavascript,问题是我仅在所有代码都已执行时才得到回调。 有什么办法可以处理这个问题或有其他更好的选择吗?

这是代码:


String[] jsonStringTagResult = new String[1];

//trying to get the value returned by patrolTagToInvoke(tagid)
webView.evaluateJavascript("patrolTagToInvoke('"+tagId+"')", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String value) {
    jsonStringTagResult[0] = value;
    }
});

//the callback from js doesn't arrive in time so jsonStringTagResult will always be null
if (jsonStringTagResult[0] != null || !jsonStringTagResult[0].isEmpty()) {
javascript java android webview callback
1个回答
0
投票
  • evaluateJavascript 的异步特性。您传递给评估Javascript 的回调不保证在执行 JavaScript 代码后立即调用。这是因为 JavaScript 代码是在 WebView 的上下文中执行的,这意味着它在不同的线程上运行。

  • 将必要的权限添加到您的 AndroidManifest.xml 文件中

  • 首先创建一个将用作 JavaScript 接口的 Java 类

    public class WebAppInterface {
      private Context context;
    
      public WebAppInterface(Context context) {
        this.context = context;
      }
    
      @JavascriptInterface
      public void sendTagResult(String tagResult) {
        // Handle the tag result here
      }
    }
    
  • 然后,将 JavaScript 接口添加到您的 WebView

    webView.addJavascriptInterface(new WebAppInterface(this), "Android");
    
  • 您可以修改 JavaScript 代码以在获得结果时调用 sendTagResult 方法

     function patrolTagToInvoke(tagid) {
       // Your existing code here
       // When you have the result, call the sendTagResult method
       Android.sendTagResult(result);
     }
    
  • 最后,在 Java 代码中,您可以重写 WebViewClient 的 onJsPrompt 方法来处理 JavaScript 代码中的提示

    webView.setWebViewClient(new WebViewClient() {
     @Override
     public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
         // Check if the message is the tag result
         if (message.startsWith("tagResult:")) {
             // Extract the tag result from the message
             String tagResult = message.substring("tagResult:".length());
             // Handle the tag result here
             // ...
             // Don't forget to call JsPromptResult.confirm to indicate that you've handled the prompt
             result.confirm("");
             // Return true to indicate that you've handled the prompt
             return true;
         }
         // If the message is not a tag result, return false to let the WebView handle the prompt
         return false;
      }
    });
    
© www.soinside.com 2019 - 2024. All rights reserved.