Objective-C与JavaScript的交互

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容