WKWebView js調(diào)用OC OC調(diào)用js.-2022-03-03

1.js調(diào)用OC WKScriptMessageHandler協(xié)議 js注入

config.userContentController = wkUController;
注意:遵守WKScriptMessageHandler協(xié)議,代理是由WKUserContentControl設(shè)置
 //這個類主要用來做native與JavaScript的交互管理
 WKUserContentController * wkUController = [[WKUserContentController alloc] init];
//注冊一個name為jsToOcNoPrams的js方法,設(shè)置處理接收JS方法的代理
 [wkUController addScriptMessageHandler:self  name:@"jsToOcNoPrams"];
 [wkUController addScriptMessageHandler:self  name:@"jsToOcWithPrams"];
config.userContentController = wkUController;
//用完記得移除
 //移除注冊的js方法
[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcNoPrams"];
[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcWithPrams"];
//通過接收JS傳出消息的name進行捕捉的回調(diào)方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
 //用message.body獲得JS傳出的參數(shù)體
NSDictionary * parameter = message.body;
//JS調(diào)用OC
 if([message.name isEqualToString:@"jsToOcNoPrams"]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js調(diào)用到了oc" message:@"不帶參數(shù)" preferredStyle:UIAlertControllerStyleAlert];
 [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 }])];

  [self presentViewController:alertController animated:YES completion:nil];
}else if([message.name isEqualToString:@"jsToOcWithPrams"]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js調(diào)用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
 [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}])];
[self presentViewController:alertController animated:YES completion:nil];
    }
}

2.JS調(diào)用OC方法。WKNavigationDelegate協(xié)議攔截
pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if ([navigationAction.request.URL.scheme caseInsensitiveCompare:@"jsToOc"] == NSOrderedSame) {
[WKWebViewInterceptController showAlertWithTitle:navigationAction.request.URL.host message:navigationAction.request.URL.query cancelHandler:nil];
decisionHandler(WKNavigationActionPolicyCancel);  
  }
    else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

3.js調(diào)用OC的彈出框, WKUIDelegate協(xié)議
//web界面中有彈出警告框時調(diào)用

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    // 確定按鈕
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:”” style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }];
    [alertController addAction:alertAction];
    if (self.visibleNavigator) {
        [self.visibleNavigator presentViewController:alertController animated:YES completion:nil];
    }else{
        completionHandler();
    }
}

#pragma mark - WKUIDelegate
//! alert(message)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        completionHandler();

    }];

    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];

}

//! confirm(message)

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Confirm" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        completionHandler(NO);    }];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        completionHandler(YES);    }];

    [alertController addAction:cancelAction];

    [alertController addAction:confirmAction];

    [self presentViewController:alertController animated:YES completion:nil];

}

//! prompt(prompt, defaultText)

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];

    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {

        textField.placeholder = defaultText;

    }];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        completionHandler(alertController.textFields[0].text);

    }];

    [alertController addAction:confirmAction];

    [self presentViewController:alertController animated:YES completion:nil];

}

2.OC調(diào)用js注入方法。 WKUserScript

以下代碼適配文本大小,由UIWebView換為WKWebView后,會發(fā)現(xiàn)字體小了很多,這應(yīng)該是WKWebView與html的兼容問題,解決辦法是修改原網(wǎng)頁,要么我們手動注入JS
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

        //用于進行JavaScript注入

        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

        [config.userContentController addUserScript:wkUScript];

        [self.webView evaluateJavaScript:@"ocToJs('loginSucceed', 'oc_tokenString')" completionHandler:^(id response, NSError *error) {}];

2.1.OC調(diào)用js注入方法 evaluateJavaScript:completionHandler

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

    [webView evaluateJavaScript:@"document.title" completionHandler:^(NSString *title, NSError *error) {

        self.title = title;

    }];

}

http://www.itdecent.cn/p/5cf0d241ae12/

http://www.itdecent.cn/p/e23aa25d7514

http://www.itdecent.cn/p/7a1fceae5880

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容