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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,786評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,656評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,697評論 0 379
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,098評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,855評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,254評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,322評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,473評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,014評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,833評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,016評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,568評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,273評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,680評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,946評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,730評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,006評論 2 374

推薦閱讀更多精彩內容