【问题标题】:WebChromeClient OnJSAlert is not called未调用 WebChromeClient OnJSAlert
【发布时间】:2015-06-13 07:09:04
【问题描述】:

我正在 WebView 中运行 JS 脚本。该脚本向 WebView 发出一条消息,我想在我的应用程序中接收它。问题是onJSAlert没有被调用,我也不能在定义方法时使用@Override注解。
我的进口是 -

import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.JsResult;
import android.webkit.WebSettings;

我像这样使用 WebView -

webView = (WebView)findViewById(R.id.webView1); 
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
            Log.d("fibi", "finished loading");
            }
        }
        //@Override //If I uncomment this I get compilation error
        public boolean onJSAlert(WebView view, String url, String message, final JsResult result) {
            encResult = message;
            Log.d("fibi", encResult);
            result.cancel();
            return true;                
        }
    });
webView.loadUrl("file:///android_asset/test.html");

而我的 test.html 的 HTML 代码是

 <html>
   <body >
     <div onclick="alert('CLICK')"> Click Me !!  </div>
   </body>
</html>

当我运行应用程序时,会加载 HTML 文件并调用 onProgressChanged - 我可以看到显示“加载完成”的日志消息。当我点击加载页面上的链接时,onJSAlert 未被调用 - 我没有收到日志消息,而是看到一个对话框窗口在我的设备上弹出并显示警报消息。
如果我尝试在onJSAlert 的开头使用@Override 注释,则会收到错误消息-“MainActivity.MyWebClient 类型的 onJSAlert(WebView, String, String, JsResult) 方法必须覆盖或实现超类型方法”。
有什么想法吗?

【问题讨论】:

  • 感谢您在示例中包含 setJavaScriptEnabled,这是让我弄清楚为什么我的警报不起作用的缺失部分(现在很明显,我的 JavaScript 也没有)。

标签: javascript android webview webchromeclient


【解决方案1】:

如果您使用没有正确拼写的方法名称,您的方法调用将不起作用

onJSAlert

改为:

onJsAlert

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    相关资源
    最近更新 更多