实现JS与OC 的互相调用,可参考这篇文章 OC与JS互调获取系统图片
这里就不讲调用的原来了,直接上解决webView中出现的提示title有地址的问题
1.首先新建扩展类继承 JavaScript 名字为 UIWebView+JavaScript 点击next,创建后报错,.h中把 @interface UIWebView_JavaScript : JavaScript 改成 @interface UIWebView (JavaScript) ; .m文件中也需要把@implementation UIWebView_JavaScript 改成 @implementation UIWebView (JavaScript);注意:如果使用了监听 Confirm则需要为Alert 挂上代理(也就需要导入代理),这样方便判断选择的是“取消”还是“确定”,或者其他的按钮。
下面是.h文件中的内容
// // UIWebView+JavaScript.h // JS和iOS交互 // // Created by user on 16/9/14. // Copyright © 2016年 user. All rights reserved. // // 这是个扩展类 #import <UIKit/UIKit.h> #import <JavaScriptCore/JavaScriptCore.h>// 引入系统框架 @interface UIWebView (JavaScript) <UIAlertViewDelegate> @end
2.现在可以实现方法的监听实现,直接在.m实现文件中实现
// UIWebView+JavaScript.m // // // Created by user on 16/9/14. // Copyright © 2016年 user. All rights reserved. // #import "UIWebView+JavaScript.h" @implementation UIWebView (JavaScript) -(void)webView:(UIWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame { NSLog(@"弹出提示++++++"); UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示:" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];// 在这里不用挂上代理 message 是webView里JS中提示的内容 [alert show]; } static BOOL diagStat = NO; static NSInteger btIndex = -1;// 区别于 alert 消失是的按钮 - (BOOL)webView:(UIWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame { UIAlertView *confirmAlert = [[UIAlertView alloc] initWithTitle:@"助手提示"message:message delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil]; // 这里必须挂上代理 message 是webView里JS中提示的内容 [confirmAlert show]; btIndex = -1; while (btIndex==-1) { //[NSThread sleepForTimeInterval:0.2]; [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]]; } if (btIndex == 0) { //取消; diagStat = NO; } else if (btIndex == 1) { //确定; diagStat = YES; } return diagStat; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { btIndex = buttonIndex; if (buttonIndex == 0) { NSLog(@"取消 按钮"); } else { NSLog(@"确定 按钮"); } } @end 使用的时候,在加载webView中导入该类的头文件即可。特别注意的是,这里是使用系统的 alertView替换html中的显示的alert并不是同一个对象,所以获取Confirm是,需要在上面的 alertViewDelegate中实现 OC调用JS的方法。