1、js 调用oc方法
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *configur = [[WKWebViewConfiguration alloc] init];
WKPreferences *preferences = [[WKPreferences alloc] init];
configur.preferences = preferences;
preferences.javascriptEnabled = YES;
self.userContentController = [[WKUserContentController alloc]init];
[self.userContentController addScriptMessageHandler:self name:@"goBack"];
configur.userContentController = self.userContentController;
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight-NaviHeight-44) configuration:configur];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.10.60/"]]];
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
}
//WKScriptMessageHandler协议方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"goBack"]) {
//做处理 do something
//message.body 为此 ScriptMessage 传递的消息内容
NSLog(@"goBack");
}
}
主要点:
- 如果message.body中无参数,JS代码中需要传个null,不然ios端不会接受到JS交互,window.webkit.messageHandlers.kJS_Login.postMessage(null)