JavaScript代码写在如下webView的代理方法中。
-(void)webViewDidFinishLoad:(UIWebView*)webView;//当网页视图结束加载一个请求之后,得到通知。
-(void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")",jsDocPathStr];
[webView stringByEvaluatingJavaScriptFromString:sendJsStr];
}
demo如下:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// 设置p标签字体颜色
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function SetParaColor() {"
"var i = 0;"
"var allP = document.getElementsByTagName('p');"
"for (i; i < allP.length; i++) {"
"var p = allP[i];"
"p.style.color = '#333';"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"
];
[webView stringByEvaluatingJavaScriptFromString:@"SetParaColor();"];
}
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"];
NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath];
[webView stringByEvaluatingJavaScriptFromString:jsString];
在JavaScript写上:
href = "$://......."
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *str = [request.URL absoluteString];
if ([str hasPrefix:@"http"]) {
NSString *url = [Utils URLDecodedString:str];
NSArray *params = [url componentsSeparatedByString:@"?"];
if (params.count > 0) {
if (params.count >=2 ) {
NSArray *value = [params[1] componentsSeparatedByString:@"="];
if ([value[0] isEqualToString:@"name"]) {
[HyperlinkClickManager hyperlinkClickWithParam:value[1] type:@"$" delegate:self.contentView.viewController titleStr:@""];
}else if ([value[0] isEqualToString:@"topicId"]) {
[HyperlinkClickManager hyperlinkClickWithParam:value[1] type:@"#" delegate:self.contentView.viewController titleStr:@""];
}else if ([value[0] isEqualToString:@"clientId"]) {
[HyperlinkClickManager hyperlinkClickWithParam:value[1] type:@"#_" delegate:self.contentView.viewController titleStr:@""];
}else if ([value[0] isEqualToString:@"fid"]) {
[HyperlinkClickManager hyperlinkClickWithParam:value[1] type:@"@" delegate:self.contentView.viewController titleStr:@""];
}else {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
}else {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
}else {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
return NO;
}
return YES;
}