传递数据从Javascript到Android的WebView [英] Passing Data From Javascript To Android WebView

查看:147
本文介绍了传递数据从Javascript到Android的WebView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一块的Java code的其目的是通过一款Android的WebView门户调用Java code从Javascript。

I have written a piece of Java code which is intended as to call Java code from Javascript by a android WebView gateway.

webView = (WebView) findViewById(R.id.captchaView);
WebSettings ws = webView.getSettings();
ws.setJavaScriptEnabled(true);
webView.loadUrl("https://google.com/");

webView.setWebViewClient(BrowserHandler);
webView.addJavascriptInterface(new IJavascriptHandler(), "cpjs");

WebViewClient BrowserHandler = new WebViewClient() {
   @Override
   public void onPageFinished(WebView view, String url) {
      view.loadUrl("javascript:window.cpjs.onPageLoaded(document.body.innerHTML);void(0);");
   }
};

final class IJavascriptHandler {
   IJavascriptHandler() {
   }

   public void onPageLoaded(String html) {
      // this is called from JS
      Toast t = Toast.makeText(getApplicationContext(), "Yes", 2000);
      t.show();
   }
}

以上code检查网页加载,一旦在页面加载完成后,它会调用它从Java暴露javascript函数,以便它可以携带我从网页所需要的。

The above code checks for web page load and once the page is finished loading, it will call javascript function which is exposed from Java so it could carry what I need from the page.

这是未按预期它的作用是简单地刷新页面每隔几秒钟。我不知道什么是错在这里?

This is not working as expected what it does is simply refresh the page every few seconds. I am not sure what is wrong here?

推荐答案

嗯,有很多事情是你做了什么很奇怪的。

Well, there are lots of things that are rather strange in what you have done.


  • 从Java,是触发的Javascript ...回调到Java的。你是假设这是安全的。

  • From Java, you are triggering Javascript...to call back into Java. You are assuming this is safe.

您正在加载的谷歌主页,当它遇到一个Android浏览器时,我最后一次检查,将执行重定向。

You are loading the Google home page, which will perform a redirect when it encounters an Android browser, the last time I checked.

您正试图显示吐司,但你不知道,如果是code将主应用程序线程上运行与否。

You are attempting to display a Toast, yet you have no idea if that code will run on the main application thread or not.

这篇关于传递数据从Javascript到Android的WebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆