UIWebView与js交互(一)


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");

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值