将javascript注入WebChromeClient [英] Inject javascript into WebChromeClient
问题描述
我知道,您可以将JavaScript注入Android WebView。我已经这样做了。但是,我加载了一个html5 / javascript网络应用程序(不是我自己的,所以我无法访问代码),我需要注入额外的JavaScript。但是这个Web应用程序在标准WebView中无法正常运行。原因可能是:
I know, you can inject javascript into an Android WebView. I already did that. However, I load a html5/javascript web app (not my own, so I have no access to the code) and I need to inject additional javascript. But this web app does not work properly in the standard WebView. The reason for that is probably:
默认情况下,WebView不提供类似浏览器的小部件,不会启用JavaScript和网页错误被忽略。
http://developer.android。 com / reference / android / webkit / WebView.html
所以,我启用了Javascript,但也许这是由于它忽略了网页错误的事实。然而,在普通的Chrome浏览器中,每件事都可以正常运行而没有任何问题
So, I enabled Javascript, but maybe this is due to the fact that it ignores webpage errors. However in the normal Chrome browser everythings works fine without any problems.
尽管我已经启用了很多东西,但webview仍无效:
The webview does not work although I already enabled a lot of stuff:
webView = (WebView) findViewById( R.id.webView );
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setDomStorageEnabled(true);
webView.setBackgroundColor(0x00000000);
webView.setWebChromeClient( new WebChromeClient() );
webView.setWebViewClient( new WebViewListener() );
CookieManager.getInstance().setAcceptCookie(true);
那么,是否有可能将javascript注入普通的WebChromeClient?
或者您还有其他猜测我还能启用或注入到webview中吗?
So, is there some possibility to inject javascript into a normal WebChromeClient? Or do you have any other guess what else I could enable or inject into the webview?
推荐答案
首先,你需要使用从WebViewClient派生的类来设置WebViewClient:
First, you need to setWebViewClient with a class that's derived form WebViewClient:
WebView webview = new WebView();
webview.setWebViewClient(new WebClient());
webview.loadUrl("stackoverflow.com");
然后在WebClient中等待页面加载(onPageFinished)。然后你loadUrl(javascript:[你的javascript在这里])。
then in WebClient, you wait for the page to load (onPageFinished). Then you loadUrl("javascript:[your javascript here]").
public class WebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url)
{
// Obvious next step is: document.forms[0].submit()
view.loadUrl("javascript:document.forms[0].q.value='[android]'");
}
}
这篇关于将javascript注入WebChromeClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!