WKWebView中JS方法调用OC方法

在html中定义方法

 methods:{
	onLineCollectionFun:function () {
	 	var u = navigator.userAgent;
	 	//android终端
     	var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; 
     	//ios终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); 
        	if(isAndroid){
                   window.android.OnLineCollectionFun();
             }else {
                   console.log('在线收款')
 					window.webkit.messageHandlers.OnLineCollectionFun.postMessage({'methodsID':'1'});
              }
	}
}

wkwebview代理设置

#import <WebKit/WebKit.h>
@interface GuestHomeController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property(nonatomic,strong) WKWebView * webView;
@property(nonatomic,weak) MBProgressHUD*hud;
@end

初始化wkwebview

WKWebView*webV=[[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:configuration];
[self.view addSubview:webV];
_webView=webV;
webV.backgroundColor=[UIColor groupTableViewBackgroundColor];
webV.UIDelegate=self;
webV.navigationDelegate=self;
NSString * urlString = @"";
urlString = [kBaseWebURL stringByAppendingString:@"guesthome"];
[webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];

第一步.我们需要在WKWebView创建的过程中初始化添加ScriptMessageHandler

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = [WKUserContentController new];
[configuration.userContentController addScriptMessageHandler:self name:@"OnLineCollectionFun"];

然后实现代理方法.监听JS的回调.为了查看效果,代码如下所示.

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    HWDLog(@"%@", message.body);
    HWDLog(@"%@", message.name);
    NSDictionary * body = [message.body objectForKey:@"body"];
    if ([message.name isEqualToString:@"OnLineCollectionFun"]) {
        [self onLineCollectController];
    }
}

WKWebView中OC方法调用JS方法

在WKWebView OC方法调用JS方法方法比较简单.我们只需要使用如下方法即可.

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;

看一下例子.在index.js中定义一个方法.方法内容为弹出一个框.代码如下所示.

function alertAction(message) {
    consule.log(message);
}
- (void)alertButtonAction{
    
    [self.mainWebView evaluateJavaScript:@"alertAction('OC调用JS方法')" completionHandler:^(id _Nullable item, NSError * _Nullable error) {
        NSLog(@"alert");
    }];
   
}
Logo

前往低代码交流专区

更多推荐