UIWebView与JS的交互

IOS-的UIWebView

    UIWebVew是ios开发中较为常用的一个控件。其可以打开网页,加载html,打开文档等。当我们在开发中需要用到一些显示页面时,UIWebView是一个很好的选择。

创建一个UIWebView


的CGRect bouds = [[UIScreen manScreen] applicationFrame];  
UIWebView的web视图* = [[UIWebView的页头] initWithFrame:方法界限]  

设置属性


//UIWebView默认允许当网页内容处于最顶端时,用户用手指往下拖动,然后露出空白的背景。这份代码能够禁止这种效果。
webView.scrollView.bounces = NO;

//是否与用​​户交互(即用户能不能控制的WebView)
[web视图setUserInteractionEnabled:YES];

//自动对页面进行缩放以适应屏幕 
webView.scalespageToFit = YES;  
//自动检测网页上的电话号码,单击可以拨打 
webView.detectsPhoneNumbers = YES; 

加载内容


NSURL * URL = [NSURL URLWithString:@“http://www.youku.com”]; //创建网址  
*的NSURLRequest请求= [的NSURLRequest requestWithURL:URL]; //创建的NSURLRequest   
[web视图的loadRequest:请求]; //加载  

加载本地HTML页面


//返回HTML文件路径
* NSString的文件路径= [[[一个NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@“homeDetail.html”];
//读取HTML文件内容
* NSString的htmlString = [NSString的stringWithContentsOfFile:文件路径编码:NSUTF8StringEncoding错误:无];
//替换HTML文件的内容
htmlString = [htmlString stringByReplacingOccurrencesOfString:@“$ {} docContent”withString:[的NSString stringWithFormat:@“%@”,[JSON objectForKey:@“内容”]]];

[web视图loadHTMLString:htmlString BASEURL:[NSURL URLWithString:文件路径]];

UIWebViewDelegate委托代理


//设置委托对象
webView.delegate =自我;

//选择要实现的委托方法
////当网页视图被指示载入内容而得到通知。应当返回YES,这样会进行加载。
- (BOOL)web视图:(UIWebView的*)web视图shouldStartLoadWithRequest:(*的NSURLRequest)reuqest navigationType:(UIWebViewNavigationType)navigationType;   
//通过导航类型参数(navigationType)可以得到请求发起的原因,可以是以下任意值:
UIWebViewNavigationTypeLinkClicked  
UIWebViewNavigationTypeFormSubmitted  
UIWebViewNavigationTypeBackForward  
UIWebViewNavigationTypeReload  
UIWebViewNavigationTypeFormResubmitted  
UIWebViewNavigationTypeOther  

//当网页视图已经开始加载一个请求后,得到通知。
- (无效)webViewDidStartLoad:(UIWebView的*)web视图;
//当网页视图结束加载一个请求之后,得到通知。
- (无效)webViewDidFinishLoad:(UIWebView的*)web视图; 
//当在请求加载中发生错误时,得到通知。会提供一个NSSError对象,以标识所发生错误类型。 
- (无效)web视图:(UIWebView的*)web视图DidFailLoadWithError:(NSError *)错误;  

[参考] http://blog.csdn.net/toss156/article/details/7303425


与JavaScript的的交互

    stringByEvaluatingJavaScriptFromString方法可以将javascript嵌入页面中,通过这个方法我们可以在iOS中与UIWebView中的网页元素交互。

    我们在webViewDidFinishLoad方法中就可以通过JavaScript的操作界面元素了。

获取当前页面的URL。


- (无效)webViewDidFinishLoad:(UIWebView的*){web视图  
  * NSString的CURRENTURL = [web视图stringByEvaluatingJavaScriptFromString:@“document.location.href”];
}

获取页面标题:


- (无效)webViewDidFinishLoad:(UIWebView的*){web视图  
   * NSString的CURRENTURL = [web视图stringByEvaluatingJavaScriptFromString:@“document.location.href”];

   * NSString的标题=的WebView stringByEvaluatingJavaScriptFromString:@“document.title时”]; 
}

修改界面元素的值。


的NSString * js_result = [web视图stringByEvaluatingJavaScriptFromString:@“document.getElementsByName('Q')[0]。价值=”AAA“;”];

表单提交


* NSString的js_result2 = [web视图stringByEvaluatingJavaScriptFromString:@“document.forms [0] .submit();”];

插入JS代码

我们可以封装到一个JS函数中,将这个函数插入到页面上执行,代码如下:



- (无效)webViewDidFinishLoad:(UIWebView的*){web视图

    //拦截网页图片并修改图片大小
    [web视图stringByEvaluatingJavaScriptFromString:
     @“VAR脚本=使用document.createElement('脚本');”
     “script.type =”文/ JavaScript的“;”
     “script.text = \”功能ResizeImages(){“
     “VAR myimg,oldwidth;”
     “VAR了maxWidth = 300;” //缩放系数
     “对于(i = 0;我 <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('头')[0] .appendChild(脚本);”];
    //
    [web视图stringByEvaluatingJavaScriptFromString:@“ResizeImages();”];
}

[参考]http://www.cnblogs.com/zhuqil/archive/2011/08/03/2126562.html


响应图片长按事件


静态的NSString * const的kTouchJavaScriptString =
@“document.ontouchstart =函数(事件){\
X = event.targetTouches [0] .clientX; \
Y = event.targetTouches [0] .clientY; \
document.location = \“MyWeb即可:触摸:启动:\”+ X + \“:\”+ Y;};“;

- (无效)webViewDidFinishLoad:(UIWebView的*){web视图
[web视图stringByEvaluatingJavaScriptFromString:kTouchJavaScriptString];
}

//功能:UIWebView的响应长按事件
- (BOOL)web视图:(UIWebView的*)web视图shouldStartLoadWithRequest:(*的NSURLRequest)要求navigationType:(UIWebViewNavigationType)navigationType {

    * NSString的requestString = [[URL请求] absoluteString]
    NSArray的*组件= [requestString componentsSeparatedByString:@“”];
    如果([组件数]> 1 && [(的NSString *)[成分objectAtIndex:0]
                                   isEqualToString:@“MyWeb即可”]){
        如果([(的NSString *)[成分objectAtIndex:1] isEqualToString:@“触摸”])
        {
            如果([(的NSString *)[成分objectAtIndex:2] isEqualToString:@“开始”])
            {
                / *
                 @需延时判断是否响应页面内的JS ...
                 * /
                self.gesState = GESTURE_STATE_START;

                浮PTX = [[成分objectAtIndex:3]的floatValue]
                浮PTY = [[成分objectAtIndex:4]的floatValue]

                * NSString的JS = [的NSString stringWithFormat:@“document.elementFromPoint(%F,%F).tagName”,PTX,PTY]
                * NSString的标签名= [self.webView stringByEvaluatingJavaScriptFromString:JS];
                self.imgUrl =零;
                如果([标签名isEqualToString:@“IMG”]){
                    self.imgUrl = [的NSString stringWithFormat:@“document.elementFromPoint(%F,%F)的.src”,PTX,PTY]
                }
                如果(self.imgUrl){
                    self.timer = [的NSTimer scheduledTimerWithTimeInterval:0.5目标:自我选择:@选择(handleLongTouch :)用户信息:无重复:NO];
                }
            }
        }
        返回NO;
    }
    返回YES;

}


//功能:如果点击的是图片,并且按住的时间超过1秒,执行handleLongTouch函数。
- (无效)handleLongTouch:(*的NSTimer)定时器{
    如果(self.imgUrl && self.gesState == GESTURE_STATE_START){

        self.gesState = GESTURE_STATE_END;
        HomeDetailImageViewController * imageViewController = [[HomeDetailImageViewController的alloc]初始化];
        imageViewController.imgUrlStr = [self.webView stringByEvaluatingJavaScriptFromString:self.imgUrl];
        [self.navigationController pushViewController:imageViewController动画:是];

    }
}

[参考] http://www.tuicool.com/articles/j6fmY3j

 

 

在UIWebView的内容加载完之后,可以利用javascript获取其页面内的数据,核心就是通过UIWebView的方法:

NSString *string = [awebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('field_2').value;" ];

以下是一些常用的js脚本:

thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
thisTLoc = top.location.href;
thisPLoc = parent.document.location;
thisTHost = top.location.hostname;
thisHost = location.hostname;
thisTitle = document.title;
thisProtocol = document.location.protocol;
thisPort = document.location.port;
thisHash = document.location.hash;
thisSearch = document.location.search;
thisPathname = document.location.pathname;
thisHtml = document.documentElement.innerHTML;
thisBodyText = document.documentElement.innerText;//获取网页内容文字
thisBodyText = document.body.innerText;//获取网页内容文字

 

也可以通过同样的方法去设置页面内容(比如帮用户输入表单数据)
比如:
NSString *string = [awebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('field_2').value='a value';" ];
就可以修改field_2的值了

同样也可以去模拟页面内按钮的点击,提交页面,比如:
document.getElementById('aButtonName').click();
或者,假设知道按钮是第几个input标签(假设为第一个)
document.getElementsByTagName('input').item(0).click();
也可以设置checkBox的状态:
document.getElementById('aCheckBoxId').checked=true;

参考:
http://hi.baidu.com/zfpp25/blog/item/0bc5e3565a7e632e0cf3e3d7.html
http://www.cnblogs.com/del/archive/2009/01/07/1370907.html
http://blog.csdn.net/studyrecord/article/details/6213843

posted @ 2016-04-21 18:07  w_only  阅读(671)  评论(0编辑  收藏  举报