1.Xcode create a new my. HTML file and customize the HTML content. The main code is as follows:

(1) The tag is UI style (simple JS code is written to explain the interaction)

(2) for JS onClick event, when JS want to pass an argument to the OC, using the following code window. Its. MessageHandlers. : < name >. PostMessage (data)

<h1 style="text-align:center; background-color: #e6b500; wdith:100px; height:40px""> <p style=" max-width: 100%; clear: both; min-height: 1em"text-align:center"> <a href="github://callName_? https://github.com/wslcmk"<p style= "max-width: 100%; clear: both"text-align:center"> <a href="http://192.168.0.116/monkey/iOS-URNetworking/commits/master"<p style= "max-width: 100%; clear: both; min-height: 1em"text-align:center"> <button id="btn1" type = "button" onclick = "jsToOcFunctionOne()"<p style= "padding-top: 0px; padding-bottom: 0px"text-align:center"> <button id="btn2" type = "button" onclick = "jsToOcFunctionTwo()"<p style= "padding-top: 0px; padding-bottom: 0px"text-align:center"> <button id="btn3" type = "button" onclick = "showAlert()"</button> </p> <! -- JS syntax --> <scripttype = "text/javascript">
    
function jsToOcFunctionOne()
{
   window.webkit.messageHandlers.jsToOcNoPrams.postMessage({});
}

function jsToOcFunctionTwo()
{
    window.webkit.messageHandlers.jsToOcWithPrams.postMessage({"params":"I'm a JS parameter"});
}

function showAlert()
{
    alert("I'm from the JS world and you found me."); } // Change the background colorfunction changeBgColor()
{
    document.body.style.backgroundColor = randomColor();
}
Copy the code

2.KVO realizes loading progress bar and title

Get the title and display [self.webView addObserver:selfforKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
   [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
   if ([keyPath isEqualToString:@"title"]&&object == _webView) {
       self.title = _webView.title;
   }else if ([keyPath isEqualToString:@"estimatedProgress"]
             && object == _webView)
   {
       self.progressView.progress = _webView.estimatedProgress;
       if(_webView estimatedProgress > = 1.0 f) {dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.progressView.progress = 0; }); }}}Copy the code

WKNavigationDelegate delegate (WKNavigationDelegate delegate)

Pragma mark -- WKNavigationDelegate Handles jump and load operations- (void) WebView :(WKWebView *) WebView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString * urlStr = navigationAction.request.URL.absoluteString; NSLog(@"Send a jump request: %@",urlStr); // Self-defined protocol header NSString *htmlHeadString = @"github://";
   if([urlStr hasPrefix:htmlHeadString]){
       UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Call OC by intercepting URL" message:@"To making?" preferredStyle:UIAlertControllerStyleAlert];
       [alertController addAction:([UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           
       }])];
       [alertController addAction:([UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           NSURL * url = [NSURL URLWithString:[urlStr stringByReplacingOccurrencesOfString:@"github://callName_?" withString:@""]];
           [[UIApplication sharedApplication]canOpenURL:url];
       }])];
       [self presentViewController:alertController animated:YES completion:nil];
       decisionHandler(WKNavigationActionPolicyCancel);
   }else{ decisionHandler(WKNavigationActionPolicyAllow); }}Copy the code

4.OC gets JS alert content (WKUIDelegate handles warnings, input, and validation, and only alerts are listed here. Input and prompt functions are triggered by the confirm and prompt functions on the JS side.

When calling the alert function on the JS side: Get the alert content through the following proxy

#pragma mark -- WKUIDelegate WKUIDelegate handles javascript scripts, validation boxes, warning boxes, etc
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"JS-alert-Action"message:message? : @"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
Copy the code

EvaluateJavaScript; jsString; evaluateJavaScript; evaluateJavaScript;

#pragma mark -navigationItem Action- (void)ocToJs {// changeColor() is the JS method name NSString *jsString = [NSString stringWithFormat:@"changeBgColor()"];
    [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
       
    }];
}
Copy the code

6. By accepting JS method name capture method (with and without parameters, pass an argument to the IOS JS end, by the window. Its. MessageHandlers. < method name >. PostMessage (data))

(1) WKUserContentController needs to be introduced. The main code is as follows

WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; WKUserContentController * wkUController = [[WKUserContentController alloc] init]; / / register a name for jsToOcNoPrams js method sets the receive handler js object [wkUController addScriptMessageHandler: self name: @"jsToOcNoPrams"];
        [wkUController addScriptMessageHandler:self  name:@"jsToOcWithPrams"];
        config.userContentController = wkUController;
Copy the code

(2) Core code

#pragma mark - A callback method that is captured by receiving the name of the JS outgoing message
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo); NSDictionary * parameter = message.body; NSDictionary * parameter = message.body; / / JS calls the OCif([message.name isEqualToString:@"jsToOcNoPrams"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Js called oc" message:@"No parameters" 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 called oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"OK"style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }])]; [self presentViewController:alertController animated:YES completion:nil]; }}Copy the code