js 與WKWebView 互動

mindX發表於2019-03-25

實現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];
複製程式碼

相關文章