js 与WKWebView 交互

395 阅读1分钟

实现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];