[iOS]WKWebView之MesssageHandler

本文介绍了iOS中的WKWebView使用MessageHandler进行JS与原生交互的机制,包括如何注入JS方法、JS如何调用OC方法以及具体的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、什么是MessageHandler

 

MessageHandler是WKWebView用来处理原生与JS交互的消息处理机制。也即是说:JS要想调用iOS原生的方法,可以采用MessageHandler。

 

二、怎么注入js的方法

WKWebView在创建的时候有一个属性:WKWebViewConfiguration,这个configuration有个WKUserContentController类型的属性:userContentController。在userContentController中我们是通过:addScriptMessageHandler:name方法来注入js的方法的。

- (void)addScriptMessageHandler:(id<WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;

参数:scriptMessageHandler是userContentController的代理对象;

参数:name是js方法名。

可以多次调用此方法或者说注入多个MessageHandle来注入多个js的方法。

三、js如何调用OC的方法

WKWebView通过实现WKScriptMessageHandler代理协议来调用OC的方法。此协议只有一个代理方法。

- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message 

API文档是这么说的:

/*! @abstract Invoked when a script message is received from a webpage.
 @param userContentController The user content controller invoking the
 delegate method.
 @param message The script message received.
 */

参数message有个属性:

1、body: 可以理解为js传过来的参数。可以是字典,字符串等,客户端接收到之后用来调oc的方法。

@discussion Allowed types are NSNumber, NSString, NSDate, NSArray,
 NSDictionary, and NSNull.

2、name:可以理解为js的方法名称。客户端接收到后针对不同的消息进行判断逻辑处理。

四、demo

.h

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface STBaseWebViewController : UIViewController

@property (nonatomic, copy) NSString *urlStr;
@property (nonatomic, strong) NSArray *jsArr;

@end

NS_ASSUME_NONNULL_END

.m

#import "STBaseWebViewController.h"

@interface STBaseWebViewController ()<WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSArray *jsFuncArr;

@end

@implementation STBaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.webView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
}

- (WKWebView *)webView
{
    if (_webView) {
        WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
        WKPreferences *preferences = [WKPreferences new];
        preferences.minimumFontSize = 10;
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        configuration.preferences = preferences;
        configuration.userContentController = [WKUserContentController new];
        
        // injection JS function
        for (NSString *funcStr in self.jsFuncArr) {
            [configuration.userContentController addScriptMessageHandler:self name:funcStr];
        }
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height - 44) configuration:configuration];
    }
    
    return _webView;
}

- (NSArray *)jsFuncArr {
    if (!_jsFuncArr) {
        _jsFuncArr = [NSArray array];
    }
    
    return _jsFuncArr;
}

#pragma mark - WKScriptMessageHandler
// js call oc
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
    // name: function name
    // body: js->oc parameters such as Dictionary...
    if ([message.name isEqualToString:@"takePhoto"]) {
        // call oc methord
        if ([message.body isKindOfClass:[NSDictionary class]]) {
            NSString *title = message.body[@"title"];
            NSString *content = message.body[@"contentt"];
            NSLog(@"js pass value to oc:[title:%@ content:%@]",title,content);
            // ...
        }
    } else if ([message.name isEqualToString:@"otherFunction"]){ // ... otherFunction
        
    } else {
        // oc call js
        NSString *title = @"OC调用JS";
        NSString *content = @"执行evaluateJavaScript方法,在completionHandler里面处理回调";
        NSString *jsFunc = [NSString stringWithFormat:@"jsShare('%@','%@')",title,content];
        [self.webView evaluateJavaScript:jsFunc completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            NSLog(@"result--->%@",result);
        }];
    }
}

- (void)takePhoto {
    NSLog(@"take photo...");
}

@end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值