关键部分:
<meta name="viewport" content="width=device-width, initial-scale=1"> webview.loadUrl("javascript:var imgs=document.getElementsByTagName(‘img‘);for(var i=0;i<imgs.length;i++){imgs[i].style.width=‘320px‘;};void(0);");
需要在加载的HTML中在<head></head>标签中加入这句话,用于页面适应手机屏幕;
loadUrl函数是通过模拟a标签跳转时的时候调用JS脚本,以完成注入的目的;
测试HTML内容代码:
<html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> </head> <body> <img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/> <img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/> <img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/> <img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/> </body> </html>
Android Class WebView代码:
String content = "<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head><body><img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/><img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/><img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/><img src=\"/wyfs02/M02/45/DA/wKioL1PsdWqTvMWZAABqd73eyHI527_middle.jpg\"/></body></html>"; webview = (WebView) findViewById(R.id.demoView); webview.getSettings().setJavaScriptEnabled(true); webview.loadDataWithBaseURL("http://s3.51cto.com", content, "text/html", "utf-8", null); webview.setWebViewClient(new WebViewClient(){ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); webview.loadUrl("javascript:var imgs=document.getElementsByTagName(‘img‘);for(var i=0;i<imgs.length;i++){imgs[i].style.width=‘320px‘;};void(0);"); } });
Android Activity 代码:
<android.webkit.WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/demoView" ></android.webkit.WebView>
Android AndroidManifest.xml 写入相关权限
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.demo" > <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ..... </manifest>
注意事项:
1、权限不能忘记了,要不然访问请求不到页面;
2、网页描述那一段最好加上“<meat name=....”这段;
webview.loadUrl("javascript:var imgs=document.getElementsByTagName(‘img‘);for(var i=0;i<imgs.length;i++){imgs[i].style.width=‘320px‘;};void(0);");
JS脚本注入后面加上 void(0),因为页面会跳转所以根据以前的前端经验我加上了这一句,至于为什么模拟A标签的时候写了javascript:xxxx,页面还是会跳转请路过高手们能告诉我感激不尽
本文出自 “Bruce-Zhang” 博客,请务必保留此出处http://brucezhang51.blog.51cto.com/6252580/1759459
原文地址:http://brucezhang51.blog.51cto.com/6252580/1759459