您的位置:首页 > 移动开发

UIWebView与js交互(一)

2015-08-17 15:07 531 查看
UIWebView与js交互

UIWebView与js交互,关键在于stringByEvaluatingJavaScriptFromString;它可以实现从js获取title等内容还可以给js发送数据。

具体如下:

- (void)webViewDidFinishLoad:(UIWebView *)webView;在webViewDidFinishLoad方法里面,通过如下方式可以获取你需要的内容:

1、获取当前网页的网址

//获取当前网页的网址

NSString * currentUrl = [webViewstringByEvaluatingJavaScriptFromString:@"document.location.href"];

NSLog(@"currentUrl:%@",currentUrl);
2、获取当前网页的title

//获取当前网页的title

NSString * currentUrlTitle = [webViewstringByEvaluatingJavaScriptFromString:@"document.title"];

NSLog(@"currentUrlTitle:%@",currentUrlTitle);

3、获取整个html页面的js代码

//整个html页面的js代码

NSString * allHTML = [ webViewstringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
NSLog(@"someHTML:%@",allHTML);

第一步:

UIWebView * myWebView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(myTextField.frame)+leftSpace,SCREEN_WIDTH,SCREEN_HEIGHT-CGRectGetMaxY(myTextField.frame)+leftSpace)];

myWebView.backgroundColor = [UIColorgrayColor];
myWebView.scalesPageToFit =YES;
myWebView.delegate =self;
[self.viewaddSubview:myWebView];
self.myWebView = myWebView;

[selfrequestUrl];
第二步:

-(void)requestUrl
{

[selfshouldresignFirstResponder];

NSURLRequest * request = [NSURLRequestrequestWithURL:[NSURLURLWithString:self.myTextField.text]];
[self.myWebViewloadRequest:request];
}
第三步:

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{

NSLog(@"1::shouldStartLoadWithRequest");

return
YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{

NSLog(@"2::webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{

NSLog(@"3::webViewDidFinishLoad");

//获取当前网页的网址

NSString * currentUrl = [webViewstringByEvaluatingJavaScriptFromString:@"document.location.href"];

NSLog(@"currentUrl:%@",currentUrl);

self.myTextField.text = currentUrl;

//获取当前网页的title

NSString * currentUrlTitle = [webViewstringByEvaluatingJavaScriptFromString:@"document.title"];

NSLog(@"currentUrlTitle:%@",currentUrlTitle);

self.title = currentUrlTitle;

//整个html页面的js代码

NSString * allHTML = [ webViewstringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];

NSLog(@"someHTML:%@",allHTML);
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{

NSLog(@"4::didFailLoadWithError");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: