標籤:
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/----百度一下
iOS:在OC中調用JS指令碼:樣本一