第二步:给需要注入的资源文件在url上做一个标志,当然,你也可以不做,只要你在安卓端可以判断出来即可。
<link rel="stylesheet" href="[inject]public/css/bootstrap.min.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="[inject]public/css/bootstrap-theme.min.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" src="[inject]public/js/zipto/1.1.6/zepto.min.js"></script>
<script type="text/javascript" src="[inject]public/js/modules/md5.min.js"></script>
第三步:拦截将要注入的文件,读取本地文件即可。
webview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//System.out.println("WebResourceResponse::"+url)
if(url.contains("[inject]")){
String localPath = url.replaceFirst("^http.*inject\\]","")
System.out.println("LocalPath::"+localPath)
try {
InputStream is = getApplicationContext().getAssets().open(localPath)
return new WebResourceResponse("text/javascript", "UTF-8", is)
} catch (Exception e) {
e.printStackTrace()
return super.shouldInterceptRequest(view, url)
}
} else {
return super.shouldInterceptRequest(view, url)
}
}
})
Android和IOS上都有WebView,做起来很省事。当然这时就要考虑如何在Android或iOS中实现与网页的交互。对iOS而言,包括如何在网页中调用OC,以及如何在OC中对网页进行操作。先将网页弄到iOS项目中:
网页内容如下, 仅供测试:
<html> <head> <meta xmlns="http://www.w3.org/1999/xhtml" http-equiv="Content-Type" content="text/htmlcharset=utf-8" /> <title>这是一个示例html文件</title> <script Type='text/javascript'> function clickme() { alert('点击按钮了!') } </script> </head> <body> <h1>OC与JS互动</h1> <h2>blog.csdn.net/xn4545945</h2> <!-- 自定义协议与OC进行交互 --> <a href="neng://loadUrl/blog.csdn.net">点击一下, 链接调用OC函数</a> <br/> <br/> <a href="http://m.baidu.com">js注入, 到baidu页面上实验</a> </body> </html>
第一步:将资源拷贝到assets目录第二步:给需要注入的资源文件在url上做一个标志,当然,你也可以不做,只要你在安卓端可以判断出来即可。第三步:拦截将要注入的文件,读取本地文件即可。webview.setWebViewClient(newWebViewClient(){@OverridepublicWebResourceResponseshouldInterceptRequest(WebViewview,Stringurl){//System.out.println("WebResourceResponse::"+url)if(url.contains("[inject]")){StringlocalPath=url.replaceFirst("^http.*inject\\]","")System.out.println("LocalPath::"+localPath)try{InputStreamis=getApplicationContext().getAssets().open(localPath)returnnewWebResourceResponse("text/javascript","UTF-8",is)}catch(Exceptione){e.printStackTrace()returnsuper.shouldInterceptRequest(view,url)}}else{returnsuper.shouldInterceptRequest(view,url)}}})