iOS_捕捉JSAlert/confirm事件

利用iOS原生代码为壳,加载Html代码的过程中,进行alert或者confirm进行信息提示的时候,会出现下图的情况:
这里写图片描述

这个时候,就需要捕捉alert或者confirm的事件,以便处理提示框显示的样式。


捕捉alert或者confirm的事件,代码如下:

@implementation UIWebView (JavaScriptAlert)

- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ensureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:ensureAction];

    UIViewController *rootViewController = [UIApplication sharedApplication].windows.firstObject.rootViewController;
    [rootViewController presentViewController:alertController animated:YES completion:nil];
}
static BOOL clickState = NO;
static NSInteger btnIndex = -1;
- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
    NSString *otherButtonText = @"确定";
    NSString *cancelButtonText = @"取消";
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clickActionButton:0];
    }];
    UIAlertAction *ensureAction = [UIAlertAction actionWithTitle:otherButtonText style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clickActionButton:1];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:ensureAction];
    UIViewController *rootViewController = [UIApplication sharedApplication].windows.firstObject.rootViewController;
    [rootViewController presentViewController:alertController animated:YES completion:nil];
    btnIndex = -1;
    while (btnIndex == -1) {
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
    }
    if (btnIndex == 0){
        // 取消
        clickState = NO;
    }else if (btnIndex == 1) {
        // 确定
        clickState = YES;
    }
    return clickState;
}
- (void)clickActionButton:(NSInteger)buttonIndex{
    btnIndex = buttonIndex;
}


@end

经测试结果如图所示:
这里写图片描述


代码地址:
https://github.com/FlyingKuiKui/JSMutuallObjectC.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值