替换UIWebView中JS的Alert

写一个UIWebView的分类UIWebView+JavaScriptAlert

1.UIWebView+JavaScriptAlert.h

#import 
#import 

NS_ASSUME_NONNULL_BEGIN

@protocol JavaScriptAlertDelegate

@optional
- (void)webView:(UIWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message;

@end


@interface UIWebView (JavaScriptAlert)

- (void)webView:(UIWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString * _Nullable)message initiatedByFrame:(id _Nullable)frame;
- (void)setJSDelegate:(id)jsDelegate;

@end

NS_ASSUME_NONNULL_END

2.UIWebView+JavaScriptAlert.m

#import "UIWebView+JavaScriptAlert.h"
#import 

const void *JSAlertDelegate = "JavaScriptAlertDelegate";

@implementation UIWebView(JavaScriptAlert)

- (void)webView:(UIWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
    
    [[self getJSDelegate] webView:webView runJavaScriptAlertPanelWithMessage:message];
}

- (void)setJSDelegate:(id)jsDelegate {
    
    objc_setAssociatedObject(self, JSAlertDelegate, jsDelegate, OBJC_ASSOCIATION_ASSIGN);
}

- (id)getJSDelegate {
    
    return objc_getAssociatedObject(self, JSAlertDelegate);
}

@end

3.实现位置

1.遵循代理
2.设置代理[self.webView setJSDelegate:self];
3.实现代理方法
#pragma mark - JavaScriptAlertDelegate - NativeAlert替换JS的alert
-(void)webView:(UIWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message{
    
    UIAlertView *webAlert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [webAlert show];
}

你可能感兴趣的:(替换UIWebView中JS的Alert)