iOS UIWebView重写或者监听js Alter/Confirm/Prompt函数

最近公司在开发web型的app,涉及许多交互,刚好,我遇到js中 的Alter/Confirm/Prompt三个弹框提示函数的坑,今天记录解决的办法下来,供大家使用。

1、在开发过程中,前端使用了他们自己的弹框框架,结果在iOS和Android端展示这样子,多了http。

77F9F95B-E8C0-4A10-A931-964055A4E9BD.png

2、为了解决这样的问题,百度了许多,最终借助百度上的资料和官方文档,试验成功了。
3、其实不难解决这个问题,新建个UIWebView类别,在m文件写上如下代码,即可。

  • (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(CGRect *)frame {
UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

[customAlert show];

}
static BOOL diagStat = NO;

static NSInteger bIdx = -1;

  • (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame{

    diagStat = NO;

    bIdx = -1;

    UIAlertView *confirmDiag = [[UIAlertView alloc] initWithTitle:@"温馨提示"
    message:message
    delegate:self
    cancelButtonTitle:@"取消"
    otherButtonTitles:@"确定", nil];

    [confirmDiag show];

    while (bIdx==-1) {
    //[NSThread sleepForTimeInterval:0.2];
    [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
    }
    if (bIdx == 0){//取消;
    diagStat = NO;
    }
    else if (bIdx == 1) {//确定;
    diagStat = YES;
    }
    return diagStat;
    }

  • (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    bIdx = buttonIndex;
    }

  • (NSString *) webView:(UIWebView *)view runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(id)frame{

    diagStat = NO;

    bIdx = -1;
    UIAlertView *confirmDiag = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:prompt
    delegate:self
    cancelButtonTitle:@"取消"
    otherButtonTitles:@"确定", nil];

[confirmDiag setAlertViewStyle:UIAlertViewStylePlainTextInput];

UITextField *textField = [confirmDiag textFieldAtIndex:0];
textField.placeholder = @"请输入信息";
textField.keyboardType = UIKeyboardTypeDefault;


[confirmDiag show];

while (bIdx==-1) {
    //[NSThread sleepForTimeInterval:0.2];
    [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1f]];
}
if (bIdx == 0){//取消;
    diagStat = NO;
}
else if (bIdx == 1) {//确定;
    diagStat = YES;
}
return textField.text;

效果如下:


7616FF80-91D4-498B-B439-DB7660AE8DED.png

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容