UIWebView是iOS最常用的SDK之一,它有一個stringByEvaluatingJavaScriptFromString方法可以將javascript嵌入頁面中,通過這個方法我們可以在iOS中與UIWebView中的網頁元素交互。
stringByEvaluatingJavaScriptFromString
使用stringByEvaluatingJavaScriptFromString方法,需要等UIWebView中的頁面加載完成之后去調用。我們在界面上拖放一個UIWebView控件。在Load中將google mobile加載到這個控件中,代碼如下:
復制代碼
- (void)viewDidLoad
{
[super viewDidLoad];
webview.backgroundColor = [UIColor clearColor];
webview.scalesPageToFit =YES;
webview.delegate =self;
NSURL *url =[[NSURL alloc] initWithString:@"http://www.google.com.hk/m?gl=CN&hl=zh_CN&source=ihp"];
NSURLRequest *request =? [[NSURLRequest alloc] initWithURL:url];
[webview loadRequest:request];
}
復制代碼
我們在webViewDidFinishLoad方法中就可以通過javascript操作界面元素了。
1、獲取當前頁面的url。
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
}
2、獲取頁面title:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
NSString *title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];
}
3、修改界面元素的值。
NSString *js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='朱祁林';"];
4、表單提交:
NSString *js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit(); "];
這樣就實現了在google搜索關鍵字:“朱祁林”的功能。
5、插入js代碼
上面的功能我們可以封裝到一個js函數中,將這個函數插入到頁面上執行,代碼如下:
復制代碼
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function myFunction() { "
"var field = document.getElementsByName('q')[0];"
"field.value='朱祁林';"
"document.forms[0].submit();"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
復制代碼
看上面的代碼:
a、首先通過js創建一個script的標簽,type為'text/javascript'。
b、然后在這個標簽中插入一段字符串,這段字符串就是一個函數:myFunction,這個函數實現google自動搜索關鍵字的功能。
c、然后使用stringByEvaluatingJavaScriptFromString執行myFunction函數。
實例:
////? WebNewsViewController.m//? EzyCloud////? Created by Umbrella on 15/12/22.//? Copyright ? 2015年 CloudTech. All rights reserved.//#import "WebNewsViewController.h"#import "UIView+Extension.h"#import "NSString+HCStringSIze.h"#import "MLKMenuPopover.h"#import "CloudCall2AppDelegate.h"@interface WebNewsViewController ()@property (nonatomic,copy) NSString *currentTitle;
@property (nonatomic,copy) NSString *currentURL;
@property (nonatomic,weak) UIWebView *webView;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,weak) MLKMenuPopover *menuPopover;
@end
@implementation WebNewsViewController
- (void)viewDidLoad {
[super viewDidLoad];
//添加webView
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, screenWith, screenHeight - 64)];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
webView.scalesPageToFit = YES;
[self.view addSubview:webView];
self.webView = webView;
self.webView.delegate = self;
//初始化導航欄
[self initialNavigation];
}
- (void)initialNavigation{
//導航欄左邊按鈕設置
UIView *leftView = [[UIView alloc]init];
//左邊返回按鈕
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImageView *backImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
backImgView.image = [UIImage imageNamed:@"back_normal_icon"];
UILabel *backLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(backImgView.frame),0,44,22)];
backLabel.font = [UIFont systemFontOfSize:17];
backLabel.textColor = [UIColor whiteColor];
backLabel.text = AppLocalizedString(@"Back");
backLabel.width = [backLabel.text sizeWithFont:backLabel.font maxW:60].width;
[backBtn addSubview:backImgView];
[backBtn addSubview:backLabel];
backBtn.frame = CGRectMake(0, 0,CGRectGetMaxX(backLabel.frame), 22);
[backBtn addTarget:self action:@selector(onClickBack) forControlEvents: UIControlEventTouchUpInside];
[leftView addSubview:backBtn];
//左邊關閉按鈕
UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UILabel *closeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0,44,22)];
closeLabel.font = [UIFont systemFontOfSize:17];
closeLabel.text = AppLocalizedString(@"Close");
closeLabel.textColor = [UIColor whiteColor];
closeLabel.width = [closeLabel.text sizeWithFont:closeLabel.font maxW:60].width;
[closeBtn addSubview:closeLabel];
closeBtn.frame = CGRectMake(CGRectGetMaxX(backBtn.frame) + 5, 0,closeLabel.width, 22);
[closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[closeBtn addTarget:self action:@selector(onClickClose) forControlEvents: UIControlEventTouchUpInside];
[leftView addSubview:closeBtn];
leftView.frame = CGRectMake(0, 0, CGRectGetMaxX(closeBtn.frame), 22);
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView] ;
//設置導航欄右邊按鈕
UIButton *rightBarbtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,44, 44)];
rightBarbtn.imageEdgeInsets = UIEdgeInsetsMake(0, 14, 0, 0);
[rightBarbtn setImage:[UIImage imageNamed:@"three_point_normal_icon"] forState:UIControlStateNormal];
[rightBarbtn setImage:[UIImage imageNamed:@"three_point_down_icon"] forState:UIControlStateHighlighted];
[rightBarbtn addTarget:self action:@selector(rightBarbtnClick) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarbtn];
self.navigationItem.rightBarButtonItem = rightBarItem;
//設置導航欄中間部分
CGFloat titleLabelX = CGRectGetMaxX(leftView.frame)+5;
UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(titleLabelX, 0, screenWith - titleLabelX - rightBarbtn.width,22)];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.font = [UIFont systemFontOfSize:17];
self.navigationItem.titleView = titleLabel;
self.titleLabel = titleLabel;
}
#pragma mark - 導航欄事件
-(void)rightBarbtnClick{
BOOL isEN = [CloudCall2AppDelegate sharedInstance].appLanguageType == AppLanguageTypeEN;
NSArray *menuItems;
NSArray *menuIcons;
menuItems = [NSArray arrayWithObjects:AppLocalizedString(@"Send to Chat"),AppLocalizedString(@"Share on Moments"),AppLocalizedString(@"Open the browser"),nil] ;
menuIcons = @[@"friend_ic",@"friends-r_ic",@"earth"];
MLKMenuPopover *menuPopover = [[MLKMenuPopover alloc] initWithFrame:CGRectMake(screenWith-(isEN?205:165),75,isEN?200:160,187) menuItems:menuItems menuIcons:menuIcons];
self.menuPopover = menuPopover;
self.menuPopover.menuPopoverDelegate = self;
[self.menuPopover showInView:[UIApplication sharedApplication].keyWindow];
}
/**
*? 下拉菜單的選擇代理方法
*
*? @param menuPopover
*? @param selectedIndex
*/
- (void)menuPopover:(MLKMenuPopover *)menuPopover didSelectMenuItemAtIndex:(NSInteger)selectedIndex{
switch (selectedIndex) {
case 0:
{
//發送給朋友
}
break;
case 1:
{
//分享到朋友圈
}
break;
case 2:{
NSURL *theURL = [self.webView.request URL];
NSString *urlString = [theURL absoluteString];
if ([urlString rangeOfString:@"Language="].location == NSNotFound ) {
urlString = [NSString stringWithFormat:@"%@/?Language=%@",urlString,[[CloudCall2AppDelegate sharedInstance] getCurrentLangageForHttp]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
} else {
[[UIApplication sharedApplication] openURL:theURL];
}
}
break;
default:
break;
}
}
//導航欄返回按鈕
- (void)onClickBack{
if ([self.webView canGoBack]) {
[self.webView goBack];
}else {
[self onClickClose];
}
}
//導航欄關閉按鈕
- (void)onClickClose{
[self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark webView代理
//獲取頁面title
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.currentURL = [self.webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
self.currentTitle = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
self.titleLabel.text = self.currentTitle;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end