WKWebView与js交互

WKWebView与js交互

//  ViewController.m
#import "ViewController.h"
#import 

@interface ViewController () 

@property (nonatomic, strong) WKWebView *wkWebView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建一个webiview的配置项
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

    // 通过js与webview内容交互配置
    config.userContentController = [[WKUserContentController alloc] init];
    //在状态栏显示或隐藏,活动指示器,默认为NO
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    // 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    
    self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];
    
    self.wkWebView.navigationDelegate=self;
    
    
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
//加载本地的html
    [self.wkWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
 
    [self.view addSubview:self.wkWebView];

    //
    WKUserContentController *userCC = config.userContentController;
    //OC注册供JS调用的方法
    /*
     window.webkit.messageHandlers.showMobile.postMessage
     [userCC addScriptMessageHandler:self name:@"showMobile"];
     这两行代码是对应的。
     
     */
    [userCC addScriptMessageHandler:self name:@"HtmlActivationAPPforNull"];
    [userCC addScriptMessageHandler:self name:@"HtmlActivationAPPforBookName"];
    [userCC addScriptMessageHandler:self name:@"HtmlActivationAPPforData"];
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"铺抓加载前的URL的来源=%@",webView.URL);
    NSLog(@"铺抓加载前的URL=%@",navigationAction.request.URL);
    return decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"完成加载啦");
}


/**
 //网页加载完成之后调用JS代码才会执行,因为这个时候html页面已经注入到webView中并且可以响应到对应方法

 @param sender 用Storyboard建的三个button
 */
- (IBAction)btnClick:(UIButton *)sender {
    
    if (!self.wkWebView.loading) {
        if (sender.tag == 123) {
             NSLog(@"按钮123《APP触发HTML界面》被点击");
            [self.wkWebView evaluateJavaScript:@"APPActivationHtml()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                //TODO
                NSLog(@"response=%@ 。error=%@",response,error);
            }];
        }
        
        if (sender.tag == 234) {
             NSLog(@"按钮234《APP触发并给HTML传参数》被点击");
            [self.wkWebView evaluateJavaScript:@"alertName('除了问号这一段文字都是APP传给html的')" completionHandler:nil];
        }
        
        if (sender.tag == 345) {
             NSLog(@"按钮345《APP触发并给HTML传多个参数》被点击");
            [self.wkWebView evaluateJavaScript:@"alertSendMsg('18870707070','周末OC')" completionHandler:nil];
            [self showMsg:@"懂了吗"];

        }

    } else {
        NSLog(@"the view is currently loading content");
    }
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"%@",NSStringFromSelector(_cmd));
    NSLog(@"message.name=%@",message.name);
    NSLog(@"message.body=%@",message.body);

    if ([message.name isEqualToString:@"HtmlActivationAPPforNull"]) {
        [self showMsg:@"我是HTML触发,APP的原生提示框"];
    }
    if ([message.name isEqualToString:@"HtmlActivationAPPforBookName"]) {
        NSString *info = [NSString stringWithFormat:@"书名号中的文字《%@》, 是HTML传给APP",message.body];
        [self showMsg:info];
    }
    
    if ([message.name isEqualToString:@"HtmlActivationAPPforData"]) {
        NSArray *array = message.body;
        NSString *info = [NSString stringWithFormat:@"书名号中文字都是Html传给app的《%@》,《 %@》",array.firstObject,array.lastObject];
        
      [self.wkWebView evaluateJavaScript:@"alertNam('OCOC')" completionHandler:nil];

        [self showMsg:info];
    }
}

- (void)showMsg:(NSString *)msg {
    
    [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"点击OK", nil] show];
    _wkWebView.backgroundColor =[UIColor blueColor];
    
}
- (IBAction)clear:(id)sender {
    NSLog(@"清除被点击");
    [self.wkWebView evaluateJavaScript:@"clear('清除你')" completionHandler:nil];
}


@end
WKWebView与js交互_第1张图片
Snip20170920_3.png

本地的html代码:


    
    
        
        我的HTML
        
        
        
        
    

    
    
        



如果文章帮到您,喜欢点个赞,谢谢您。
文章内容出错,记得留言,感激不尽。

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