写一个UIWebView的分类UIWebView+JavaScriptAlert
1.UIWebView+JavaScriptAlert.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol JavaScriptAlertDelegate<NSObject>
@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 <objc/runtime.h>
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<JavaScriptAlertDelegate>)jsDelegate {
objc_setAssociatedObject(self, JSAlertDelegate, jsDelegate, OBJC_ASSOCIATION_ASSIGN);
}
- (id<JavaScriptAlertDelegate>)getJSDelegate {
return objc_getAssociatedObject(self, JSAlertDelegate);
}
@end
3.实现位置
1.遵循代理<JavaScriptAlertDelegate>
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];
}