标签:
1.首先导入JavaScriptCore.framework这个框架
2.创建webView、设置代理、请求手机端百度
#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ViewController ()<UIWebViewDelegate>
@property (strong,nonatomic)UIWebView *webView;
@property (assign,nonatomic)BOOL isFirstLoadWeb;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
self.webView.scalesPageToFit = YES;
self.webView.backgroundColor = [UIColor clearColor];
self.webView.delegate = self;
[self.view addSubview:self.webView];
NSURL *URL = [NSURL URLWithString:@"http://m.baidu.com"];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:URL];
[self.webView loadRequest:request];
}
3.通过代理方法,在里面调用自定义的JS脚本
-(void)webViewDidFinishLoad:(UIWebView *)webView{
//程序会一直调用该方法,所以判断若是第一次加载后使用我们自定义的js,此后不再调用JS,否则会出现网页抖动现象
if (!_isFirstLoadWeb) {
_isFirstLoadWeb = YES;
//获取当前页面的url
NSString *url = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
//获取页面的title
NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
NSLog(@"%@----%@",url,title);
//给webView添加一个自定义的JavaScript
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement(‘script‘);"
"script.type = ‘text/javascript‘;"
"script.text = \"function myFuncation(){"
"var field = document.getElementsByName(‘word‘)[0];"
"field.value = ‘夏先森的博客园‘;"
"document.forms[0].submit();"
"}\";"
"document.getElementsByTagName(‘head‘)[0].appendChild(script);"];
//开始调用自定义的JavaScript
[webView stringByEvaluatingJavaScriptFromString:@"myFuncation();"];
}else{
return;
}
}
@end
演示截图如下:
2016-04-18 21:37:24.670 OC调用JS[7568:356964] https://m.baidu.com/----百度一下
标签:
原文地址:http://www.cnblogs.com/XYQ-208910/p/5405997.html