天天看點

ios UIWebView截獲html并修改便簽内容

需求:混合應用uiwebview打開html後,uiwebview有左右滾動條,要去掉左右滾動效果; 

方法:通過js截獲uiwebview中的html,然後修改html标簽内容; 

執行個體代碼: 

伺服器端html

ios UIWebView截獲html并修改便簽内容

<html><head>  

<meta http-equiv="content-type" content="text/html; charset=utf-8">  

<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">   

<title>網曝四川省一考場時鐘慢半小時 老師稱這就是命</title></head<body>網曝四川省一考場時鐘慢半小時 老師稱這就是命</body></html>  

這樣顯示的結果網頁的最小寬度會是device-width;但有時候不需要這個寬度,就需要修改width=device-width為width=mywidth; 

用戶端代碼

ios UIWebView截獲html并修改便簽内容

- (void)webviewdidfinishload:(uiwebview *)webview  

{     

    //修改伺服器頁面的meta的值  

    nsstring *meta = [nsstring stringwithformat:@"document.getelementsbyname(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webview.frame.size.width];  

    [webview stringbyevaluatingjavascriptfromstring:meta];  

}  

這樣問題就可以解決了 

新增代碼: 

ios UIWebView截獲html并修改便簽内容

//給網頁增加utf-8編碼  

 [webview stringbyevaluatingjavascriptfromstring:  

 @"var taghead =document.documentelement.firstchild;"  

  "var tagmeta = document.createelement(\"meta\");"   

  "tagmeta.setattribute(\"http-equiv\", \"content-type\");"   

  "tagmeta.setattribute(\"content\", \"text/html; charset=utf-8\");"   

  "var tagheadadd = taghead.appendchild(tagmeta);"];  

ios UIWebView截獲html并修改便簽内容

//給網頁增加css樣式  

    [webview stringbyevaluatingjavascriptfromstring:  

     @"var taghead =document.documentelement.firstchild;"  

     "var tagstyle = document.createelement(\"style\");"   

     "tagstyle.setattribute(\"type\", \"text/css\");"   

     "tagstyle.appendchild(document.createtextnode(\"body{padding: 20pt 15pt}\"));"  

     "var tagheadadd = taghead.appendchild(tagstyle);"];  

ios UIWebView截獲html并修改便簽内容

//攔截網頁圖檔  并修改圖檔大小        

[webview stringbyevaluatingjavascriptfromstring:  

 @"var script = document.createelement('script');"   

 "script.type = 'text/javascript';"   

 "script.text = \"function resizeimages() { "   

     "var myimg,oldwidth;"  

     "var maxwidth=380;" //縮放系數   

     "for(i=0;i <document.images.length;i++){"   

         "myimg = document.images[i];"  

         "if(myimg.width > maxwidth){"   

             "oldwidth = myimg.width;"   

             "myimg.width = maxwidth;"   

             "myimg.height = myimg.height * (maxwidth/oldwidth);"   

         "}"   

     "}"   

 "}\";"   

 "document.getelementsbytagname('head')[0].appendchild(script);"];   

[webview stringbyevaluatingjavascriptfromstring:@"resizeimages();"];  

其他html屬性重載和此方法類似; 

參考網址: 

(stringbyevaluatingjavascriptfromstring的使用方法)http://www.uml.org.cn/mobiledev/201108181.asp   

( iphone 擷取uiwebview内html方法)http://blog.csdn.net/diyagoanyhacker/article/details/6564897 

(ios uiwebview引用外部css樣式)http://hi.baidu.com/jwq359699768/item/780879e5c98bfb3e4ddcaf22 

http://blog.csdn.net/xdonx/article/details/6973521