iOS WKWebView与js交互

WKWebView在执行内存上圆圆高于UIWebView

不多说直接上代码

不管是移除网页内容,还是给图片,按钮添加点击,都是一个套套路,找节点,如果不会找节点,Web开发会

#import "ViewController.h"
#import 

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    webView.navigationDelegate = self;
    [self.view addSubview:webView];
    NSURL *url = [NSURL URLWithString:@"http://m.dianping.com/tuan/deal/5501525"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}


/*
 *
 *  页面加载完成时候调用   JS注入
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    NSMutableString *MString = [NSMutableString string];
    
    // 删除网页内不需要的内容
    
    //1. 顶部的返回 --> 起名字 结尾要加;
    [MString appendFormat:@"var headerTag = document.getElementsByTagName('header')[0];"];
    //删除时需要找到父标签 --> 自己干掉自己, 下不去手
    //parentNode:父标签
    //removeChild:移除子标签内容
    [MString appendFormat:@"header.parentNode.removeChild(header);"];
    [MString appendFormat:@"var buy  = document.getElementsByClassName('buy-now ')[0];"];
    [MString appendFormat:@"buy.parentNode.removeChild(buy);"];
    
    //给image添加点击事件
    [MString appendString:@"var imgTag = document.getElenmentsByTagName('figure')[0].children[0];imgTag.onclick=function imgClick(){window.location.href='https://www.baidu.com'}"];
    
    
    [webView evaluateJavaScript:MString completionHandler:nil];
}
/*
 *
 *  网页即将开始时候调用,拦截标签点击发送的请求
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{

    NSString *urlString = navigationAction.request.URL.absoluteString;
    NSLog(@"%@",urlString);
    
    if ([urlString isEqualToString:@"https://www.baidu.com"]) {
        
        //fuck come fuck go
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

@end

!!!!!!!以上是oc调用js.下面来js调用oc!!!!!!

#import "ViewController.h"
#import 
#import 

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height

@interface ViewController ()

@property (strong, nonatomic)   WKWebView                   *webView;
@property (strong, nonatomic)   UIProgressView              *progressView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"图片下载测试";
    
    //初始话WKWebView
    [self initWKWebView];
    
    //初始化进度条
    [self initProgressView];
    //
    //添加进度条监听
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

- (void)initWKWebView{
    
    //进行配置控制器
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
    //实例化对象
    configuration.userContentController = [WKUserContentController new];
    
    [configuration.userContentController addScriptMessageHandler:self name:@"imgClick"];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 40.0;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
    
    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"saner.html" ofType:nil];
    NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    
}


- (void)initProgressView{
    
    CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
    progressView.tintColor = [UIColor redColor];
    progressView.trackTintColor = [UIColor lightGrayColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
}


#pragma mark - KVO
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

//当把JS返回给控制器,然后弹窗就是这样设计的
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    NSLog(@"%@",message);
    completionHandler();
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    if ([message.name isEqualToString:@"imgClick"]) {
        [self downImage:message.body[@"url"]];
    }
}

-(void)downImage:(NSString *)url{
    
    NSArray *images = @[url];
    [XLPhotoBrowser showPhotoBrowserWithImages:images currentImageIndex:0];
    
}

html





    
        
            
            
    
    
        

    


你可能感兴趣的:(iOS WKWebView与js交互)