Objective-C與JavaScript的交互

UIWebView是iOS最常用的SDK之一,它有一個(gè)stringByEvaluatingJavaScriptFromString方法可以將javascript嵌入頁(yè)面中,通過(guò)這個(gè)方法我們可以在iOS中與UIWebView中的網(wǎng)頁(yè)元素交互。

stringByEvaluatingJavaScriptFromString

使用stringByEvaluatingJavaScriptFromString方法,需要等UIWebView中的頁(yè)面加載完成之后去調(diào)用。我們?cè)诮缑嫔贤戏乓粋€(gè)UIWebView控件。在Load中將google mobile加載到這個(gè)控件中,代碼如下:

復(fù)制代碼

- (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];

}

復(fù)制代碼

我們?cè)趙ebViewDidFinishLoad方法中就可以通過(guò)javascript操作界面元素了。

1、獲取當(dāng)前頁(yè)面的url。

- (void)webViewDidFinishLoad:(UIWebView *)webView {

NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];

}

2、獲取頁(yè)面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(); "];

這樣就實(shí)現(xiàn)了在google搜索關(guān)鍵字:“朱祁林”的功能。

5、插入js代碼

上面的功能我們可以封裝到一個(gè)js函數(shù)中,將這個(gè)函數(shù)插入到頁(yè)面上執(zhí)行,代碼如下:

復(fù)制代碼

[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();"];

復(fù)制代碼

看上面的代碼:

a、首先通過(guò)js創(chuàng)建一個(gè)script的標(biāo)簽,type為'text/javascript'。

b、然后在這個(gè)標(biāo)簽中插入一段字符串,這段字符串就是一個(gè)函數(shù):myFunction,這個(gè)函數(shù)實(shí)現(xiàn)google自動(dòng)搜索關(guān)鍵字的功能。

c、然后使用stringByEvaluatingJavaScriptFromString執(zhí)行myFunction函數(shù)。

實(shí)例:

////? 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;

//初始化導(dǎo)航欄

[self initialNavigation];

}

- (void)initialNavigation{

//導(dǎo)航欄左邊按鈕設(shè)置

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];

//左邊關(guān)閉按鈕

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] ;

//設(shè)置導(dǎo)航欄右邊按鈕

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;

//設(shè)置導(dǎo)航欄中間部分

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 - 導(dǎo)航欄事件

-(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:

{

//發(fā)送給朋友

}

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;

}

}

//導(dǎo)航欄返回按鈕

- (void)onClickBack{

if ([self.webView canGoBack]) {

[self.webView goBack];

}else {

[self onClickClose];

}

}

//導(dǎo)航欄關(guān)閉按鈕

- (void)onClickClose{

[self.navigationController popToRootViewControllerAnimated:YES];

}

#pragma mark webView代理

//獲取頁(yè)面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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容