WKWebView與vuejs交互

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");
    }];
   
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章