广州APP开发,微信开发,广州英趣信息科技开发部博客:
UIWebView 是常用的界面控件之一,经常需要在app中使用改组件加载服务端网页或本地的网页,即使是网页那就少不了javascript,iOS SDK 为我们提供了与javascript交互的接口,UIWebView 的stringByEvaluatingJavaScriptFromString方法,使用也很简单,只需要在UIWebViewDelegate 的-(void)webViewDidFinishLoad:(UIWebView *)webView 调用即可。
注意的一点是,需要网页加载完毕才可以与javascript交互。
Sample Code:
在viewDidLoad中添加
UIWebView * webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
webView.delegate = self;
webView.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
webView.scalesPageToFit = YES;
NSURL * url = [NSURL URLWithString:@"http://www.google.com.hk/m?gl=CN&hl=zh_CN&source=ihp"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[self.view addSubview:webView];
实现UIWebViewDelegate的 -( void )webViewDidFinishLoad:( UIWebView *)webView 方法
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//取得url
NSString * currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
//取得标题
NSString * title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
//设置表单
NSString * js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='ios';"];
//提交表单
NSString * js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit();"];
NSLog(@"%@,%@,%@,%@",currentURL,title,js_result,js_result2);
}