实现delegate WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler
js调起oc的方法
注入要和js交互的方法
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
[userContentController addScriptMessageHandler:self name:@"splitGotoWebPage"];
[userContentController addScriptMessageHandler:self name:@"splitShareDialog"];
复制代码
设置代理
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
复制代码
实现代理方法 (js 调起 oc)
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
MALog(@"%@",message.name);
MALog(@"%@",message.body);
NSString *method = [NSString stringWithFormat:@"%@:",message.name];
SEL selector = NSSelectorFromString(method);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
if ([self respondsToSelector:selector]) {
[self performSelector:selector withObject:message.body];
}
#pragma clang diagnostic pop
}
复制代码
js 要如何做
window.webkit.messageHandlers.<name>.postMessage(<messageBody>) for all
复制代码
- name 为[userContentController addScriptMessageHandler:self name:@"splitShareDialog"];中的name
- postMessage(_nonull), 如果方法的返回参数为空 不能调起oc的方法
oc 调起js
声明方法
//一个参数时
NSString *jsStr = [NSString stringWithFormat:@"function(%@)",@"abc"];
// 多个参数传递的是时候
NSString *jsStr = [NSString stringWithFormat:@"function('%@','%@')",@"abc",@"123"];
复制代码
- 如何调用
//oc 调用js
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable reponse, NSError * _Nullable error) {
MALog(@"%@",error);
}];
复制代码
- function 要和js的中的方法名是一致的
- webview 如何禁止缩放
//web页面进制缩放
NSString *js = @" $('meta[name=description]').remove(); $('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );";
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
[userContentController addUserScript:script];
复制代码