最近项目要用到综合开发,和H5的童靴使用DSBridge为中间强梁,用来实现H5和native的交互。为了调试方便,H5童鞋要求看到webview中网页的源码,以便更方便的布局H5界面。本着Android开源的精神,我想这点问题都不是事,就是把webview中的字符串显示出来吗!以为一个tostring()就能搞定呢。
结果发现不行,就去找资料,网上最早也是最多的一篇内容大概如下
1. 使能javascript:
webView.getSettings().setJavaScriptEnabled(true);
2. 编写本地接口
final class InJavaScriptLocalObj {
??? public void showSource(String html) {
??????? Log.d("HTML", html);
??? }
}
3. 向网页暴露本地接口
webView.addJavascriptInterface(newInJavaScriptLocalObj(),"local_obj");
4. 编写自己的WebViewClient,并在onPageFinished中提取网页源码。
final class MyWebViewClient extends WebViewClient{
??? public boolean shouldOverrideUrlLoading(WebView view, String url) {
??????? view.loadUrl(url);
??????? return true;
??? }
??? public void onPageStarted(WebView view, String url, Bitmap favicon) {
???????? Log.d("WebView","onPageStarted");
??????? super.onPageStarted(view, url, favicon);
??? }
??? public void onPageFinished(WebView view, String url) {
??????? Log.d("WebView","onPageFinished ");
??????? view.loadUrl("javascript:window.local_obj.showSource(''+"+
??????????????????? "document.getElementsByTagName('html')[0].innerHTML+'');");
??????? super.onPageFinished(view, url);
??? }
}
照着资料写完整,运行发现出错,死活运行不出“uncaught typeerror: window.local_obj.showSource” 提示找不到该方法。重写了几遍也没有搞定。
后来有找到第二篇资料,比对了一下核心代码都是一样的,感觉也要没戏,这时看到第二篇的注释比较多
在输出方法前加了? @JavascriptInterface? @SuppressWarnings("unused")
final class InJavaScriptLocalObj {
??? @JavascriptInterface
??? @SuppressWarnings("unused")
??? public voidshowSource(String html) {
??????? Log.d("HTML",html);
??? }
还有在调用的webclient方法前加了“@SuppressLint({"JavascriptInterface","SetJavaScriptEnabled","AddJavascriptInterface"})” 声明 这样就搞定了。
完整代码如下
public class MainActivity extends AppCompatActivity {
??? @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled", "AddJavascriptInterface"})
??? @Override
??? protected void onCreate(Bundle savedInstanceState) {
??????? super.onCreate(savedInstanceState);
??????? setContentView(R.layout.activity_main);
??????? final DWebView webView= (DWebView) findViewById(R.id.webview);
??????? webView.setJavascriptInterface(new JsApi(this));
??????? webView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj1");
??????? webView.clearCache(true);
??????? webView.loadUrl("file:///android_asset/test.html");
??????? webView.setWebViewClient(new WebViewClient(){
??????????? @Override
??????????? public void onPageFinished(WebView view, String url) {
??????????????? Log.d("WebView","onPageFinished ");
??????????????? view.loadUrl("javascript:window.local_obj1.showSource('');");
??????????????? super.onPageFinished(view, url);
??????????? }
??????? });
??? }
??? final class InJavaScriptLocalObj {
??????? @JavascriptInterface
??????? @SuppressWarnings("unused")
??????? public void showSource(String html) {
?????? ? ?? Log.d("HTML", html);
??????? }
??? }
}
参考资料:http://www.cnblogs.com/hibraincol/archive/2011/10/26/2224866.html