UIWebView加载html并调用js,html中需动态行进传值,用字符串格式方式动态添加,下面代码中有相关实现.
stringByEvaluatingJavaScriptFromString方法作用是返回运行后js结果,使用请见代码。
// // ViewController.h // WebViewTest // UIWebView加载html并调用js // Created by on 12-10-30. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIWebViewDelegate> @property (weak, nonatomic) IBOutlet UIWebView *webView; @property (strong,nonatomic) NSMutableArray *arrayLanguages; #pragma 方法 //创建webView内容方法 - (void)createWebViewContent; //创建语言界面页 - (NSString*)createLanguagePage; //返回运行后js结果 - (void)executeJSFunction:(NSString *)js; @end
// // ViewController.m // WebViewTest // // Created by on 12-10-30. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize webView; @synthesize arrayLanguages; - (void)viewDidLoad { [super viewDidLoad]; arrayLanguages = [[NSMutableArray alloc] initWithCapacity:25]; [self createWebViewContent]; } //创建web内容 - (void)createWebViewContent{ NSString *homePath = [[NSBundle mainBundle] executablePath]; NSArray *strings = [homePath componentsSeparatedByString: @"/"]; NSString *executableName = [strings objectAtIndex:[strings count]-1]; NSString *rawDirectory = [homePath substringToIndex: [homePath length]-[executableName length]-1]; NSString *baseDirectory = [rawDirectory stringByReplacingOccurrencesOfString:@" " withString:@"%20"]; NSString *imagePath = [NSString stringWithFormat:@"file://%@/map.png",baseDirectory]; NSLog(@"imagePath: %@",imagePath); NSString *htmlFile = [NSString stringWithFormat:@"file://%@/welcome.html",baseDirectory]; NSLog(@"htmlFile: %@",htmlFile); NSURL *url = [NSURL URLWithString: htmlFile]; NSData *fileData = [NSData dataWithContentsOfURL:url]; //NSData *fileData = [NSData dataWithContentsOfFile:htmlFile]; NSLog(@"fileData: %@",fileData); NSString *htmlContent = [[NSMutableString alloc] initWithData: fileData encoding:NSUTF8StringEncoding]; NSLog(@"htmlContent: %@",htmlContent); NSString *langContent = [self createLanguagePage]; //通过字符串方式还对html进行动态传值 NSString* string = [NSString stringWithFormat: htmlContent,imagePath,langContent]; NSLog(@"string:%@",string); //Load the HTML String on UIWebView [self.webView loadHTMLString:string baseURL:nil];//加载html字符串到UIWebView上(该方法极为重要) //Adjust position CGRect bounds = [[UIScreen mainScreen] bounds]; int screenWidth = bounds.size.width; int screenHeight = bounds.size.height; self.webView.frame = CGRectMake(0, 20,screenWidth, screenHeight); } //创建语言显示页 - (NSString*)createLanguagePage{ arrayLanguages = [[NSMutableArray alloc] initWithObjects: @"English",@"Deutsch",@"Français",@"Español",@"Italiano",@"Pусский",@"日本語",@"中文", @"العربية",@"বাংলা",@"ελληνικά",@"हिन्दी",@"한국어",@"Bahasa Indonesia",@"Nederlands",@"Norsk", @"اردو",@"Polski",@"Português",@"Svenska",@"தமிழ்",@"Česky",@"Türkçe",@"Tiếng Việt",@"עברית>",nil]; NSMutableString* string =[[NSMutableString alloc]initWithCapacity:1024]; //init a mutable string, initial capacity is not a problem, it is flexible for(int i = 0; i < [arrayLanguages count]; i++){ [string appendString:@"<a href=\"javascript:void(0)\" "]; [string appendString:@"style=\"color:grey;text-decoration: none; "]; [string appendString:@"font-family:'Helvetica'; font-size:14px;\" "]; [string appendString:[NSString stringWithFormat: @" onMouseDown=\"imageClicked('L%d')\">%@</a>", i,[arrayLanguages objectAtIndex:i]]]; [string appendString:@" | "]; if(i%3 == 0) [string appendString:@"<br>"];//换行 } return string; } //返回运行后js结果 - (void)executeJSFunction:(NSString *)jsCommand{ NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:jsCommand]; NSLog(@"result:%@",result); } //webview开始加载请求 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ //linking the javascript to call the iPhone control NSString *url = request.mainDocumentURL.relativePath; if(url != nil) { NSLog(@"url:%@",url); NSArray *strings = [url componentsSeparatedByString: @"/"]; NSString *token = [strings objectAtIndex:[strings count]-1]; NSString *text = @""; if([token hasPrefix:@"L"]){ int i = [[token substringFromIndex:1] intValue]; text = [NSString stringWithFormat:@"language:%@ be selected", [arrayLanguages objectAtIndex:i]]; }else{ text = [NSString stringWithFormat:@"Area:%@ be selected",token]; } //执行js后,得到html里title内容(通过执行js来获取html中的内容) NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]; NSLog(@"title :%@",title); NSString *imgSrc = [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('topimage').src;"]; NSLog(@"imgSrc :%@",imgSrc); UIAlertView* alert= [[UIAlertView alloc]initWithTitle:@"javascript message" message:text delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; return FALSE; } return TRUE; } @end
welcome.html
<html>
<head>
<meta name = "viewport" content = "initial-scale = 1.0, user-scalable = no, width = 320"/>
<title>How to build an iPhone website</title>
<script>
function imageClicked(i){
var clicked = true;
var str = ""+i;
if(str.charAt(0) != 'L'){
var id = 'area' + i;
var el = document.getElementById(id);
}
alert("调用js : "+i);
window.location="http://click/"+i;
}
function printStr(str){
return str;
}
</script>
<style type="text/css">
.borderImage {
-webkit-tap-highlight-color:rgba(0,0,0,0);
}
</style>
</head>
<body style="background-color: transparent;margin-top:0px;margin-left:0px">
<center>
<div class="borderImage">
<img id="topimage" src="%@
" border="0" height="241" width="319" usemap="#map">
<map name=map>
<area shape="rect" id="area0" coords="124,1,191,58" href="javascript:imageClicked(0)" />
<area shape="rect" id="area1" coords="36,64,97,110" href="javascript:imageClicked(1)" />
<area shape="rect" id="area2" coords="119,135,171,182" href="javascript:imageClicked(2)" />
<area shape="rect" id="area3" coords="205,26,248,60" href="javascript:imageClicked(3)" />
<area shape="rect" id="area4" coords="264,88,306,132" href="javascript:imageClicked(4)" />
<area shape="rect" id="area5" coords="272,154,313,199" href="javascript:imageClicked(5)" />
<area shape="rect" id="area6" coords="187,125,232,172" href="javascript:imageClicked(6)" />
<area shape="rect" id="area7" coords="255,1,285,26" href="javascript:imageClicked(7)" />
<area shape="rect" id="area8" coords="283,1,314,26" href="javascript:imageClicked(8)" />
</map>
</div>
%@
</center>
</body>
</html>
完整工程请见附件!