WKWebView与vuejs交互

25 篇文章 0 订阅

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");
    }];
   
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值